Skip to main content
 首页 » 编程设计

python之Django之如何查询与 "listing"对象关联的所有用户

2025年05月04日52开发

我的模型是这样的:

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

  • 每个列表对象都有一个“作者”字段

    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) 

请您参考如下方法:

我认为这很简单:

CustomUser.objects.filter(needsconfirmation__author=author)