I have a Model with a Foreign Key of "Parent"
class Item(models.Model):
parent = models.ForeignKey(Parent)
This is the FK model
class Parent(models.Model):
name = models.CharField(blank=True, max_length=100)
def __unicode__(self):
return str(self.name)
I am trying to run a query that gets all Items with a parent of "xyz" I get nothing
Item.objects.filter(parent="xyz")
When I try:
Item.objects.filter(parent.name="xyz")
Or:
Item.objects.filter(str(parent)="xyz")
I get an error:
SyntaxError: keyword can't be an expression
What is the proper way to do this?
The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list then converting the django query-set to a python set using set() and finally to a list using list() .
Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.
all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you'll definitely have a QuerySet to work with.
If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.
You can use a double underscore in the keyword passed to filter()
to access fields in a foreign key relationship. Like this:
Item.objects.filter(parent__name="xyz")
Django documentation
http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships
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