django lookups that span relationships - how to
I have an Address Model which has a ForeignKey to a Contact Model:
class Address(models.Model):
street = models.CharField(max_length=25)
postal_code = models.CharField(max_length=25)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
contact = models.ForeignKey(Contact, related_name='address to contact')
class Contact(models.Model):
salutation = models.CharField(max_length=1, choices=salutation_choices, verbose_name="salutation")
title = models.ForeignKey(Title, blank=True, null=True)
...
Now I want to filter my Contact objects based on data from the address object. Therefore I want to create a filter that span a relationship, following this part of the docu:
lookup that span relationship
I tried it like this:
result_set = Contact.objects.filter(address__street__contains='mystreet')
I'm getting the following error message:
Cannot resolve keyword 'address' into field. Choices are: address to contact, birthdate..
Actually the error message tells me that there is a field address to contact, but the question is how can I开发者_开发问答 reference it?
You've set the related_name
on Contact to address to contact
. This is the value that Django uses for the backwards relation from Contact to Address - since this isn't a valid attribute name, I'm surprised it works at all.
Remove this attribute and your lookup should work.
精彩评论