2013-05-22 25 views
0

有型號:如何對查詢中進入m2m通信的背景進行檢查?

class MyObject (models.Model): 
    name = models.CharField() 


class Day (models.Model): 
    day = models.IntegerField() 


class Month (models.Model): 
    month = models.IntegerField() 
    myobj = models.ForeignKey (MyObject) 
    days = models.ManyToManyField (Day) 

用戶與網站上的形式引入了一個月。 我提出一個要求:

MyObject.objects.filter (month__month = <month, which is entered by the user with the form> 
            <day, which is entered by the user with the form> in month__days???? 
) 

如何檢查查詢用戶輸入的日期是(目前)在M2M通信天在模型中月?

回答

0

can query M2M Fields just like you would FK relationships

day = Day.objects.get(day=1) 
Month.objects.filter(days=day) 

但是你需要在MyObjectDay之間的關係做a reverse lookup

要引用「反向」的關係,只是使用的小寫名稱模型。

day = Day.objects.get(day=5) 
month = Month.objects.get(month=3) 

MyObject.objects.filter(month__month=month, month__days=day) 
+0

工程!我使用了以下選項:MyObject.objects.filter(month__month = 3, month__days__day__exact = 5)。謝謝! – user2396461