2014-02-08 162 views
0

我想通過使用過濾條件的外鍵獲取記錄集。但不知何故,這是行不通的。我在這裏展示的模型:通過ForeignKey過濾Django QuerySet

class MessageMonitoring(models.Model): 
    MyID     = models.ForeignKey(AboutMe, null=True, blank=True, related_name='MessageMonitor') 

class AboutMe(models.Model): 
    MyGender     = models.CharField(max_length=50, choices = GENDER_CHOICES) 

在我看來,我想做到以下幾點:

recipient = AboutMe.objects.get(pk=toid) 
monitor_recip = MessageMonitoring.objects.filter(MessageMonitor_owner=recipient) 

,但我得到了以下錯誤:

Cannot resolve keyword 'MessageMonitor_owner' into field. Choices are: MyID, ... 

回答

3

我m不知道你在哪裏得到MessageMonitor_owner - 這既不是模型名稱,也不是你展示的模型中的一個領域。要過濾使用的模型和外鍵關係,你顯示,使用:

monitor_recip = MessageMonitoring.objects.filter(MyID=recipient) 

或者,如果你不需要在視圖別的接收者對象,節省一些DB通過使用針對其過濾PK而不是檢索對象:

monitor_recip = MessageMonitoring.objects.filter(MyID_id=toid) 
+0

謝謝。我已經忘記了這一點! – disruptive