python - Django 多对多过滤字段

标签 python mysql django django-views many-to-many

如果该区域包含该国家/地区,我想添加到列表中,它是区域和国家/地区模型之间的 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/

相关文章:

python - 使用列表理解查找列表中的元素,其中另一个列表中的所有元素都是因子

mysql - 如何连接 2 个明细表 - MySql

python - 我可以在第一个断言失败后测试测试的所有断言吗?

python - Twitter 应用程序中的 '__getitem__' 对象中没有属性 'set'

python - 使用 FFT 和多项式插值改变人类语音的旋律

python - 如何在 Python 中循环遍历 JSON

MySQL 联合所有列

php - MySQL Row 存储加密密码

python - 使用 mod_wsgi 部署具有域和子域的 django 应用程序

python - Django manage.py 测试