【问题标题】:Django queryset: All Model1 objects where a Model2 exists with a model1 AND the given userDjango查询集:Model2存在的所有Model1对象以及model1和给定用户
【发布时间】:2015-09-06 07:45:15
【问题描述】:

我有两个模型和一个User,关联如下:

class Model1(models.Model):
    name = models.CharField(max_length=50)
    ...


class Model2(models.Model):
    model1 = models.ForeignKey(Model1)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    ...

给定一个User,我如何获得这个查询集:

所有Model1 对象,其中存在Model2 与model1 对象和给定的User

如果我能想象这张桌子:

Model2 User Model1
1      1    1
2      1    2
3      1    2
4      1    4
5      2    1
6      2    3

我正在尝试为用户获取 Model1 的查询集,比如 user=1,这将导致 Model1 对象 [1,2,4]

【问题讨论】:

    标签: python django django-models django-orm


    【解决方案1】:

    你可以通过Model2:
    模型2.objects.filter(模型1=模型1,用户=用户)\ .values_list('model1', flat=True) \ 。清楚的()

    首先,您过滤掉所有以用户为用户的 Model2,然后创建一个不同的 Model1 列表。

    list(set([m2.model1 for m2 in Model2.objects.filter(user=user).all()]))
    

    在您的具体示例中:

    list(set([m2.model1 for m2 in Model2.objects.filter(user_id=1).all()]))
    

    更新

    也试试这个:

    Model1.objects.filter(model2__user=user)
    

    【讨论】:

    • 要么我不明白(可能),要么我的问题不清楚(也可能),具体来说,model1=model1 是什么?我不想根据特定的 Model1 对象进行过滤,我希望所有这些都通过 Model2 链接到用户
    • 我对问题进行了澄清
    • list(set([... 完美运行,不包括 Model1 的重复项。更优雅的 Model1.objects.filter(...) 也可以使用,但如果存在,则为用户提供 Model1 的副本。谢谢!
    • @nima 我正在尝试模型 UserProfile 和 Like 的 objects.filter 解决方案,就像这样:results = UserProfile.objects.filter(display_name__icontains=query, like__liker=request.user.active_profile),但它说Cannot resolve keyword 'like' into field。我能做些什么来解决这个问题?谢谢
    • @dietbacon 这意味着 UserProfile 没有通过“like”属性连接到 Like。 Like 模型中的类似内容:liker = models.ForeignKey(UserProfile, related_name='like')
    猜你喜欢
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多