How to add an model instance to a django queryset?

前端 未结 4 1792
暖寄归人
暖寄归人 2020-12-13 18:14

It seems like a django queryset behaves somehow like a python list.

But it doesn\'t support list\'s .append() method as I know.

What I want to do is like:

4条回答
  •  粉色の甜心
    2020-12-13 19:02

    No. A queryset is a representation of a query - hence the name - not an arbitrary collection of instances.

    If you really need an actual queryset rather than a list, you could try accumulating the IDs of the objects you need and then getting the objects via an __in query:

    list_of_ids = []
    list_of_ids.append(my_id)
    ...
    queryset = MyModel.objects.filter(id__in=list_of_ids)
    

    This isn't very efficient, though.

提交回复
热议问题