Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django spanning relationships

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')
like image 437
byrdr Avatar asked Nov 02 '14 04:11

byrdr


1 Answers

If you need users, you should start with users. Also, you need to filter on a specific field in Annual, ie year_id.

User.objects.filter(order__select__annual__year_id=2014)
like image 120
Daniel Roseman Avatar answered Oct 18 '22 19:10

Daniel Roseman