2014-11-02 65 views
6

我已閱讀文檔,但仍然出現錯誤。我有用戶爲目錄對象放置訂單。我想創建一個查詢,它返回所有具有包含特定目錄項的訂單的用戶。Django跨越關係

這裏是我的模型:

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') 

回答

12

如果你需要用戶,你應該從用戶開始。另外,您需要過濾Annual中的特定字段,即year_id。

User.objects.filter(order__select__annual__year_id=2014) 
+0

這樣做更有意義,從用戶開始。謝謝。我能夠通過select PK:User.objects.filter(order__select ='2')正確地查詢查詢。我想更加明確,完全像你的問題。但是,我返回了以下錯誤:關係字段不支持嵌套查找。 – byrdr 2014-11-02 13:53:07

+0

啊,沒有看到你有一個related_name定義。嘗試'order__select__annual_products__year_id – 2014-11-02 15:05:59

+0

我認爲這是正確的方式... User.objects.filter(who_ordered__select__annual_products__id = 1)或User.objects.filter(who_ordered__select__annual_products = annual_obj)相關的名稱引用應該匹配每個引用。我更新了我的答案。 – 2014-11-02 15:15:38

0

如果我得到你的問題正確的話,您的查詢是錯誤的。您的Catalog模型中沒有attribute名稱order,那麼您如何使用它進行過濾?或者我在這裏失去了什麼?

直接使用在相關領域的相關名稱引用,您可以通過使用獲得的用戶 -

# 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屬性來獲取用戶對象。