Django跨越关系

时间:2014-11-02 04:37:45

标签: django django-orm

我已阅读文档,但仍然出现错误。我有用户为目录对象下订单。我想创建一个查询,该查询返回具有包含特定目录项的订单的所有用户。

以下是我的模特:

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)

以下是我一直在尝试的查询:

 Catalog.objects.filter(order__select__annual='2014')

2 个答案:

答案 0 :(得分:12)

如果您需要用户,则应从用户开始。此外,您需要过滤年度中的特定字段,即year_id。

User.objects.filter(order__select__annual__year_id=2014)

答案 1 :(得分:0)

如果我的问题正确,那么您的查询是错误的。您的attribute模型中没有order名称Catalog,那么您如何使用它进行过滤?或者我在这里遗漏了什么?

直接使用相关字段中的相关名称引用,您可以使用 -

获取用户
# id is auto generated field or you can pass one annual_product object.
User.objects.filter(who_ordered__select__annual_products__id=1)

# OR
annual = Annual.objects.all()[0]
User.objects.filter(who_ordered__select__annual_products=annual)

一步一步如何实现同样的目标: -

# where 1 is the id of an one object in Catalog model.
# You can pass Catalog object also to filter the users
Order.objects.filter(select__id=1)

# Here is the full query 
catalog = Catalog.objects.all()[0]
orders = Order.objects.filter(select=catalog)
users = [o.user for o in orders]  # This loop isn't necessary.

现在您拥有特定于一个Catalog的所有订单,您可以通过在每个订单中使用user属性来获取用户对象。