【问题标题】:Django many-to many filter fieldDjango 多对多过滤字段
【发布时间】:2015-07-18 04:44:35
【问题描述】:

如果区域包含那个国家,我想添加到列表中,它是区域和国家模型之间的 M2M 关系。我无法获得国家代码的属性,它说“预期冒号”。 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)

通知模型.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)

【问题讨论】:

  • 请修正缩进
  • 那是帖子的问题,识别是正确的

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


【解决方案1】:

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

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

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

【讨论】:

  • 现在它会生成“'ManyRelatedManager'对象没有属性'country_set'”的错误
  • 这里的区域是什么,不是区域实例吗?直接试试:region.filter(id=country.id).exists()
  • 如果您检查模型,区域是表“通知”的属性,通过 M2M 连接到表“区域”,“国家”也通过连接到表“区域”一个M2M。 country 是一个包含国家代码的变量,我无法比较和 id 与国家代码,我想比较国家代码
  • 所以不是区域,而是 n.region?那我应该是 n.region.filter(countries__code=country).exists()
  • 是的,我一个人到了那里,如果你能更新你的答案来结束这个话题。感谢“灯”
猜你喜欢
  • 2018-06-07
  • 1970-01-01
  • 2020-03-20
  • 2016-12-13
  • 2013-01-22
  • 2014-05-25
  • 2018-05-25
  • 2021-07-10
  • 2013-08-06
相关资源
最近更新 更多