如何在查询中对进入m2m通信进行背景检查?

2024-04-16 06:43:17 发布

您现在位置:Python中文网/ 问答频道 /正文

有以下几种型号:

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通信日内(存在)


Tags: the用户whichbymodelismodelsdays
1条回答
网友
1楼 · 发布于 2024-04-16 06:43:17

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

To refer to a “reverse” relationship, just use the lowercase name of the model.

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

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

相关问题 更多 >