【问题标题】:Getting all objects with equal M2M fields获取具有相同 M2M 字段的所有对象
【发布时间】:2018-07-20 14:28:03
【问题描述】:

我正在寻找一种方法来过滤所有相同类型的对象,这些对象对 M2M 字段具有相同的查询集。

class Comment(models.Model):
    user = models.ForeignKey(User, related_name='comment_user')    
    content = models.CharField(max_length=5000, null=True)

    private_to = models.ManyToManyField(User, null=True, related_name='private_to')

给定一个评论对象,我想检索具有相同 M2M 字段的所有其他 cmets(即,如果 private_to 字段为评论返回用户 1 和用户 2,它将找到所有其他包含这两者的 cmets private_to 字段中的用户。)

有没有一种简洁的内置方法来做到这一点?

【问题讨论】:

    标签: django m2m


    【解决方案1】:

    试试this post:

    comment = Comment.objects.all()[0] # Or the comment you want to filter by.
    
    private_to_ids = list(comment.private_to.all().values_list('id', flat=True))
    comments = Comment.objects.filter(private_to__exact=private_to_ids)
    

    【讨论】:

    • 有没有办法额外获得 private_to 的所有独特组合?
    • 您的意思是 private_to m2m 的所有现有(当前分配的)组合?如果集合尚未包含在数组中,您可以获得所有评论并为每个追加 comment.private_to.all().values_list('id', flat=True) 到数组中
    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2017-10-29
    • 2013-02-24
    • 2020-01-05
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多