简体   繁体   English

如何将对象添加到queryset?

[英]How to add object to queryset?

my sample code is : 我的示例代码是:

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    user = models.ForeignKey(User, null=True)
    ....

I want do some thing like this in view : 我想做这样的事情:

user = User.objects.none()

categories = Category.objects.filter(**filter)

for category in categories:

    # my problem is here , how add user category object to queryset
    # or merge object and queryset
    user = user | category.user

this part of code is for showing problem : 这部分代码用于显示问题:

    user = user | category.user

thanx . 谢谢。

You can't do that. 你不能那样做。 A Queryset is a container for objects that satisfy a query, hence the name. Queryset是用于满足查询(即名称)的对象的容器。 It's not a container for arbitrary objects. 它不是用于任意对象的容器。

Here the correct thing to do is to query the users you need directly. 在这里,正确的做法是直接查询您需要的用户。 You can follow the relationship to the Category object by using the double-underscore syntax: 您可以使用双下划线语法来跟踪与Category对象的关系:

users = User.objects.filter(category__criteria=value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM