'ManyToManyDescriptor'类型的参数不可迭代

时间:2018-10-05 20:38:41

标签: python django django-models

我有模式:

class Subscribe(models.Model):
   class Meta:
    verbose_name_plural = 'sunscribes'

   id=models.AutoField(primary_key=True)
   name=models.CharField(max_length=30,null=False);

   owner=models.ForeignKey(User,related_name='owner', null=False, blank=True, on_delete=models.PROTECT)
   subscription = models.ManyToManyField(User,null=True,related_name='subscription') 

我需要选择该用户在列表中的所有订阅项

我的尝试

avtor=post.author # user item
subscribe=Subscribe.objects.get(avtor in Subscribe.subscription ) # get list 

错误: 类型'ManyToManyDescriptor'的参数不可迭代

帖子是Article的实例

class Article(models.Model):
    id = models.AutoField(primary_key=True)
    ...
    author = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT)

1 个答案:

答案 0 :(得分:0)

反向关系使用您在related_name中定义的名称,因此获取用户的所有订阅很简单

avtor.subscription.all()

您的错误消息来自

avtor in Subscribe.subscription

这根本没有意义。要从Subscribe开始,您需要

Subscribe.objects.filter(subscription__user=avtor)