【问题标题】:how to get all fields of related model in django instead of only id如何在 django 中获取相关模型的所有字段,而不仅仅是 id
【发布时间】:2019-04-17 01:10:15
【问题描述】:

models.py

from django.db import models

class SeekerRegister(models.Model):
    seeker_name       = models.CharField(max_length=32)
    seeker_email      = models.CharField(max_length=32)

class Social(models.Model):
    social_links      = models.CharField(max_length=256)
    user              = models.ForeignKey(access_models.SeekerRegister,on_delete=models.CASCADE,related_name='social',null=True,blank=True)

我的查询:

    >>>obj=list(SeekerRegister.objects.values('social'))
    >>>[{'social': 1}, {'social': 2}, {'social': 3}]

期待:

    [{'social_links': 'facebook.com','user':1,'seeker_name':'a'}, {'social_links': 'twitter.com','user':2,'seeker_name':'b'}, {'social_links': 'linkedin.com','user':3,'seeker_name':'c'}]

当我编写上述查询时,我只得到社会模型的 id。 我怎样才能获得所有的字段 social_links 和 user 。

请查看我的代码。

【问题讨论】:

  • 不是获取 SeekerRegister 的对象,而是获取 Social 模型的对象。 Social.objects.values('social_links', 'user')
  • 我想通过加入两个模型来获取数据。请看看我的预期结果
  • 哦!您稍后编辑了问题。

标签: django


【解决方案1】:

你可以这样试试:

SeekerRegister.objects.values('social__social_link', 'id', 'seeker_name') 

其中social__social_linksocial_linkiduser

请查看SO Answer了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多