gpt4 book ai didi

python - Django 多对多过滤字段

转载 作者:行者123 更新时间:2023-11-29 22:27:49 26 4
gpt4 key购买 nike

如果该区域包含该国家/地区,我想添加到列表中,它是区域和国家/地区模型之间的 M2M 关系。我无法获取国家/地区代码的属性,它表示“需要冒号”。if 条件中遗漏了什么?

View .py

notification = Notification.objects.filter(**condition). \
exclude(notification_user__in=users). \
order_by('notificationType__priority', '-start_date')
notifications = []

for n in notification:
print len(n.region.all())
if len(n.region.all())==0:
notifications.append(n)
else:
if (region.countries__in=country):
notifications.append(n)

通知模型.py

class Notification(models.Model):
title = models.CharField(max_length=75)
description = models.TextField()
start_date = models.DateTimeField()
end_date = models.DateTimeField()
application = models.ManyToManyField('Products.Application')
notificationType = models.ForeignKey(NotificationType)
url = models.URLField(null=True, blank=True)
region = models.ManyToManyField('Geolocations.Region', null=True, blank=True)
image = models.ImageField(null=True, blank=True)
user = models.ManyToManyField(User, through='Notification_User')

地理位置模型.py

class Country(models.Model):
code=models.CharField(max_length=2)
name=models.CharField(max_length=36)
def __unicode__(self):
return u'%s - %s' % (self.code, self.name)
class Meta:
verbose_name_plural="Countries"

class Region(models.Model):
name=models.CharField(max_length=10)
countries=models.ManyToManyField(Country)

最佳答案

region.countries__in=country 是一个赋值,因为它是在 if 语句的条件下执行的,所以您将得到“需要冒号”。

如果您想检查与某个地区相关的国家/地区,您可以执行以下操作:

# country is the country's code
n.region.filter(countries_code=country).exists()

关于python - Django 多对多过滤字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30103974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com