如何在django中获得多对多关系的结果

时间:2018-05-31 00:05:32

标签: django django-models many-to-many django-orm

我有以下关系:

class Customer(models.Model):  
    user = models.OneToOneField(User, on_delete=models.CASCADE)  

class Post(models.Model):  
    customer = models.ForeignKey('common.Customer', 
    mentions = models.ManyToManyField('common.Customer',related_name='mentions')

我希望获得帖子中提到的所有用户。我在想这样的事情:

customer = Customer.objects.get(user=request.user)
posts = Post.objects.filter(mentions__in=customer).order_by('-created_at')

这接近我想要完成的事情吗?

3 个答案:

答案 0 :(得分:0)

试试这一行

users = User.objects.filter(mentions__isnull=False)

答案 1 :(得分:0)

我在django中看到了很多这样的文档并且有效:

posts = Post.objects.filter(mentions__pk=customer.id)

答案 2 :(得分:-1)

绝对不是,我很害怕。

customer = Customer.objects.get(user=request.user)
posts = Post.objects.filter(mentions__in=customer).order_by('-created_at')

mentions__in = customer会失败,因为__in lookup期望迭代(单个客户不是)。

除此之外,该查询会为您提供所有提及customer的帖子,这也可以通过两种更直接的方式实现:

posts = Post.objects.filter(mentions=customer).order_by('-created_at')

posts = customer.mentions.order_by('-created_at') # using the 'related_name' from the customer's side

您希望获得帖子中提到的所有用户。但什么帖子?你忘了在你的问题中提到这一点。您只向我们提供了可以拥有多个帖子的当前用户(request.user) 我将猜测并展示如何在当前用户发布的帖子中提及所有其他用户 为了使该关系的related_name更清楚,我会将其更改为related_name = 'mentionend'

posts = Post.objects.filter(mentions=customer) # all posts of the current user

# all other users mentioned in those posts
users = Customer.objects.exclude(user=customer).filter(mentionend__in=posts) # using 'related_name'
# or
users = posts.mentions.exclude(user=customer)