Django - 如何查询与“列表”对象关联的所有用户

时间:2015-11-15 05:28:20

标签: python django django-models django-queryset

我的模特看起来像这样:

  • CustomUser与“Listing”对象有多对多的关系

  • 每个Listing对象都有一个“author”字段

    author = models.ForeignKey(CustomUser)
    
  • 基本上,商家信息包含作者(CustomUser)和需要确认的自定义用户。

我正在努力让所有需要确认的自定义用户对作者发布的所有商家信息进行确认。

我不确定查询的正确方法是什么。

Listing.objects.filter(author=author).needsConfirmation_set.all()

模特

class CustomUser(models.Model):
    user = models.OneToOneField(User)
    location = models.CharField(max_length=50)
    rating = models.FloatField(null=True)
    level = models.CharField(max_length=50)
    followers = models.ManyToManyField("self", related_name="followers")
    following = models.ManyToManyField("self", related_name="following")
    interested = models.ManyToManyField('Listing', related_name = 'interested', default=None)
    needsConfirmation = models.ManyToManyField('Listing', related_name = 'needsConfirmation', default=None)
    confirmed = models.ManyToManyField('Listing', related_name = 'confirmed', default=None)

class Listing(models.Model): 
    subject = models.CharField(max_length=42)
    location = models.CharField(max_length=50, default="N/A")
    description = models.CharField(max_length=500)
    author = models.ForeignKey(CustomUser)
    date = models.DateTimeField(default=timezone.now)

1 个答案:

答案 0 :(得分:5)

我认为这很简单:

CustomUser.objects.filter(needsconfirmation__author=author)