I've read the documentation but am still coming up with errors. I have Users placing Orders for Catalog objects. I'd like to create a query which returns all Users that have an Order containing a specific Catalog item.
Here are my models:
class Catalog(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField()
def __unicode__(self):
return self.name
class Annual(models.Model):
catalog = models.OneToOneField(Catalog, blank=True, null=True, related_name='annual_products')
year_id = models.IntegerField(max_length=4)
start_date = models.CharField(max_length=10)
end_date = models.CharField(max_length=10)
date = models.DateTimeField(auto_now_add=True, blank=True)
def __unicode__(self):
return unicode(self.year_id)
class Order(models.Model):
user = models.ForeignKey(User, related_name='who_ordered')
select = models.ManyToManyField(Catalog, related_name='annuals_ordered', blank=True, null=True)
def __unicode__(self):
return unicode(self.user)
Here is the query I've been trying:
Catalog.objects.filter(order__select__annual='2014')
If you need users, you should start with users. Also, you need to filter on a specific field in Annual, ie year_id.
If I got your question correctly then, your query is wrong. There is no
attribute
nameorder
inside yourCatalog
model, then how can you use it for filtering ? Or I'm missing anything here ?Directly using the related name references on the related fields, you can get the users by using -
The step by step how you can achieve the same :-
Now you have all orders specific to one
Catalog
, from this you can get the user object by using theuser
attribute in each order.