【问题标题】:how to get only results in many to many relationship in django如何在 django 中只获得多对多关系的结果
【发布时间】:2018-11-09 21:54:24
【问题描述】:

我有以下关系:

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')

这是否接近我想要完成的目标?

【问题讨论】:

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


    【解决方案1】:

    试试这条线

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

    【讨论】:

      【解决方案2】:

      我在 django 的多对多文档中看到了这一点,它确实有效:

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

      【讨论】:

        【解决方案3】:

        恐怕绝对不是。

        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) 
        

        【讨论】:

          猜你喜欢
          • 2012-09-16
          • 2021-09-28
          • 2020-06-06
          • 2019-05-22
          • 1970-01-01
          • 2017-10-03
          • 2020-07-25
          • 2020-07-21
          • 1970-01-01
          相关资源
          最近更新 更多