[英]Get foreign key value for queried object in Django
I've got a search query as follows: 我有一个搜索查询,如下所示:
ct = Classified.objects.filter(
Q(name__icontains=q) |
Q(subcategory__parent__type__icontains=q) |
Q(address__area__icontains=q) |
Q(subcategory__name__icontains=q)
).filter(active__icontains='yes').filter(address__city__name__exact=cit)
for the Classified model: 对于分类模型:
class Classified(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=256)
contact_person = models.CharField(max_length=300)
email = models.CharField(max_length=100)
address = models.ForeignKey(Address)
subcategory = models.ForeignKey(Subcategory)
phone_number = models.BigIntegerField(max_length=20, default=0)
image = models.ImageField(blank=True, upload_to='dynamic/img/')
NO = 'NO'
YES = 'YES'
APPROVAL = ((NO, 'no'), (YES, 'yes'))
active = models.CharField(choices=APPROVAL, default=NO, max_length=3)
verified = models.CharField(choices=APPROVAL, default=NO, max_length=3)
def __unicode__(self):
return self.name
where the Subcategory model is: 子类别模型为:
class Subcategory(models.Model):
id = models.AutoField(primary_key=True)
parent = models.ForeignKey(Categories, null=True, blank=True, default=1)
name = models.CharField(max_length=300)
def __unicode__(self):
return self.name
The Category table is not involved here so I've not included it. 类别表不在这里,所以我没有包括它。
In the view, I've to show a filter dropdown which is supposed to show a list of all unique subcategories for the results found in ct
. 在视图中,我将显示一个过滤器下拉列表,该下拉列表应显示ct
找到的结果的所有唯一子类别的列表。
I tried two solutions: 我尝试了两种解决方案:
getsubcat = Classified.objects.filter(
Q(name__icontains=q) |
Q(subcategory__parent__type__icontains=q) |
Q(address__area__icontains=q) |
Q(subcategory__name__icontains=q)
).filter(active__icontains='yes').\
filter(address__city__name__exact=cit).values('subcategory')
This gave me a list of all subcategories as: {'subcategory': 1},{'subcategory':2}
. 这给了我所有子类别的列表: {'subcategory': 1},{'subcategory':2}
。 However this is not what I need as I need the exact Subcategory.name
for the result in ct
. 但这不是我所需要的,因为我需要ct
结果的确切Subcategory.name
。
I tried the second method in the template as: 我尝试了模板中的第二种方法:
{% for subcat in result %}
{{ subcat.subcategory.name }}
{% endfor %}
where result
is passed from the views.py as { 'result': ct, }
. result
从views.py作为{ 'result': ct, }
传递。 This however repeated the same subcategory n
number of times where n
is the number of results in result
. 但是,这重复了相同的子类别n
次,其中n
是result
。
如果需要子类别,则应查询子类别。
Subcategory.objects.filter(classified__in=ct)
I think you can use values_list
to return only the subcategory__name
. 我认为您可以使用values_list
仅返回subcategory__name
。
Try something like 尝试类似
subcategories = ct.values_list('subcategory__name', flat=True).distinct()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.