[英]Filtering Django QuerySet by ForeignKey
我想使用過濾器術語通過外鍵獲取記錄集。 但是,這不起作用。 我在這里顯示模型:
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, ...
我不確定在哪里獲取MessageMonitor_owner
這既不是模型名稱,也不是您顯示的模型上的字段。 要使用顯示的模型和外鍵關系進行過濾,請使用:
monitor_recip = MessageMonitoring.objects.filter(MyID=recipient)
或者,如果在視圖中不需要接收者對象做其他任何事情,請通過過濾其PK而不是檢索對象來節省一些數據庫的使用:
monitor_recip = MessageMonitoring.objects.filter(MyID_id=toid)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.