开发者

Django concatenate a db object with empty QuerySet

开发者 https://www.devze.com 2023-02-15 00:32 出处:网络
I have created an empty QuerySet in django like this. empty = classname.objects.none() and I have an object of same class (called class).

I have created an empty QuerySet in django like this.

empty = classname.objects.none() 

and I have an object of same class (called class).

cla开发者_Python百科ss

I want a new QuerySet having 'class' in it.

There is no append method on EmptyQuerySet and | and & do not work for the db object.


>>> empty = Person.objects.none()

if you use get you return a db object and get this error when you try use | to append the object to the empty qs:

>>> qs = empty|Person.objects.get(pk=1)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/dev/.virtualenvs/dev/lib/python2.7/site-packages/django/db/models/query.py", line 1018, in __or__
    return other._clone()
AttributeError: 'Person' object has no attribute '_clone'

however you can use the | operator to combine two query sets. To get the object as a query set we can use .filter():

>>> qs = empty|Person.objects.filter(pk=1)
>>> print qs
[<Person: A>]
>>> qs = qs|Person.objects.filter(pk=2)
>>> print qs
[<Person: A>, <Person: B>]
>>> 
0

精彩评论

暂无评论...
验证码 换一张
取 消