Python 如何在 Django 视图中获取特定字段的外键值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26986342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get ForeignKey value for specific field in Django view
提问by Ayush
I have two models defined in my models.py:
我的models.py中定义了两个模型:
class model1(models.Model):
name = models.CharField(max_length=100, unique=True)
desc = models.CharField(max_length=1000, blank=True, null=True)
def __unicode__(self):
return u'ID: %s, name - %s, description - %s' % (str(self.pk), self.name, self.desc)
class model2(models.Model):
description = models.CharField(max_length=500, blank=True, null=True)
repo_id = models.ForeignKey(model1, to_field='id', db_column="repo_id", null=False)
content = models.TextField(blank=True)
def __unicode__(self):
return u'ID: %s, rpt_repo_id - %s, created_date - %s' % (str(self.pk), str(self.repo_id.pk), self.created_date)
I want to query from model2 to fetch name from model1 where id(pk) of model1 is value from rpt_repo_id of model2. Below query doesn't work here:
我想从模型 2 查询以从模型 1 中获取名称,其中模型 1 的 id(pk) 是模型 2 的 rpt_repo_id 中的值。下面的查询在这里不起作用:
saved_reports = models.model2.objects.all()
Although {{ repo_id.name }}works fine in html.
虽然{{ repo_id.name }}在 html 中工作正常。
采纳答案by Burhan Khalid
You use the same technique in your view, as you did in your template:
您在视图中使用相同的技术,就像在模板中一样:
saved_reports = model2.objects.all()
for report in saved_reports:
print('ID: {} Name: {}'.format(report.repo_id.pk, report.repo_id.name))
If you know the id of the model1 object, and want to use that to fetch the model2 object:
如果您知道 model1 对象的 id,并想使用它来获取 model2 对象:
model2.objects.filter(repo_id__pk=1)
Django automatically creates reverse relationshipsfor foreign keys. This means that if you have a model1object, you can get its related model2object, even if you only defined the foreign key in the model2object:
Django 自动为外键创建反向关系。这意味着如果你有一个model1对象,你可以得到它相关的model2对象,即使你只在model2对象中定义了外键:
model1.objects.get(pk=1).model2_set.all() # Fetch me all model2 for this model1
回答by Geo Jacob
change str(self.repo_id.pk)to str(self.repo_id.id)
更改str(self.repo_id.pk)为str(self.repo_id.id)
回答by Geo Jacob
There is no field 'name' in model2(), it is in related table model1()
在model2()中没有字段'name',它在相关表model1()中
saved_reports = model2.objects.all()
for r in saved_reports:
print r.repo_id.name

