I'd like to get a QuerySet (to feed a ModelChoiceField) listing all objects that have an empty ForeignKey on the related set.
An example extract of my models:
class Bankcard(models.Model):
name = models.CharField(max_length=128)
number = models.IntegerField()
...
class Person(models.Model):
bankcard = models.ForeignKey(Bankcard, blank=True, null=True)
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
...
In a form I'd like to list all bank cards that have not been linked to a person yet.
What I tried is to do my own filtering as part of a list:
bankcards = Bankcard.objects.all()
unbound_cards = []
for card in bankcards:
if len(card.person_set.all()) == 0:
unbound_cards.append(card)
... but that doesn't work as I need to provide a QuerySet to the ModelChoiceField and not a list and I get 'list' object has no attribute 'all'
.
So I tried filtering directly on the related set:
unbound_cards = Bankcard.objects.filter(person_set__isnull = True)
That doesn't work either: django.core.exceptions.FieldError: Cannot resolve keyword 'person_set' into field. Choices are: ...
Any idea?
Working with Filter Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data. In this tutorial we will be querying data from the Members table.
The exclude() method from the QuerySet class returns all objects that do not match the given keyword arguments. So whatever data matches the parameter that is passed into the exclude() method will be excluded from the returned QuerySet.
Try:
Bankcard.objects.filter(person__isnull=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With