试图查询外键引用某个字段中具有特定值的条目的所有对象

2024-09-30 22:18:47 发布

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

标题可能看起来有点混乱。然而,我想做的很简单。我有以下型号:

class ListEntry(models.Model):
    name = models.CharField(max_length=64)
    expire_date = models.DateField('date of expiration')
    create_date = models.DateField('date created')

class ListWarning(models.Model):
    mailing_list = models.ForeignKey(ListEntry)
    first_warning = models.BooleanField()
    last_warning = models.BooleanField()

我想查询引用具有特定名称的邮件列表的列表警告对象。下面是一个例子:

first_warning_list = ListWarning.objects.filter(mailing_list.name='PH_212', first_warning=True, last_warning=False)

然而,出于某种原因,python抱怨语法错误:

first_warning_list = ListWarning.objects.filter(mailing_list.name='PH_212', first_warning=True, last_warning=False)
SyntaxError: keyword can't be an expression

执行此查询的语法正确方法是什么


Tags: name列表datemodelmodelslistclassfirst
1条回答
网友
1楼 · 发布于 2024-09-30 22:18:47

使用双下划线而不是点符号来表示邮件列表名称

first_warning_list = ListWarning.objects.filter(mailing_list__name='PH_212', first_warning=True, last_warning=False)

文件here.

Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.

相关问题 更多 >