Newtt
Newtt

Reputation: 6190

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.

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}. However this is not what I need as I need the exact Subcategory.name for the result in ct.

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, }. This however repeated the same subcategory n number of times where n is the number of results in result.

Upvotes: 1

Views: 483

Answers (2)

Rod Xavier
Rod Xavier

Reputation: 4043

I think you can use values_list to return only the subcategory__name.

Try something like

subcategories = ct.values_list('subcategory__name', flat=True).distinct()

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599630

If you need subcategories, you should query subcategories.

Subcategory.objects.filter(classified__in=ct)

Upvotes: 1

Related Questions