sk. nurujjaman
sk. nurujjaman

Reputation: 67

Filter queryset on a foreignkey

It might be not new to all and need your expert guidance. I am trying to filter a column on a django-table2. Note I have not used django-filter here.

class Group(models.Model):
    title = models.CharField(blank=True)

class Control(models.Model):
   published = models.charField(auto_now=False)
   group = models.ForeignKey(Group, on_delete=models.CASCADE)

Now I am trying to filter in views.py as below

table = ControlTable(Control.objects.all().order_by('-published').filter(
            group__in=form['contact'].value(),
        )

Issue is this is working fine, but when selecting '-----' from dropdown then its showing blank table instead of all the values. Again if I change the query filter as below

table = ControlTable(Control.objects.all().order_by('-published').filter(
                Group__title__iexact=form['contact'].value(),
            )

then throwing error Cannot resolve keyword 'Group' into field.

Could you please guide me on this?

Upvotes: 1

Views: 47

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477666

That makes sense, if you select ----, then it uses None, so you are filtering for None. You should check for that:

items = ControlTable(Control.objects.all().order_by('-published')
group = form['contact'].value()
if group:
    items = items.filter(
        group__in=group
    )
table = items

Upvotes: 1

Related Questions