Django 多对多过滤字段

Django many-to many filter field

如果区域包含那个国家,我想添加到列表中,它是区域和国家模型之间的 M2M 关系。我无法获取国家代码的属性,上面写着 "colon expected"。 if 条件中遗漏了什么?

views.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)

通知models.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')

地理位置models.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 语句的条件下执行的,所以你得到 "colon expected".

如果您想检查某个国家/地区是否与某个地区相关,您可以这样做:

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