Django merge db object with empty QuerySet

I created an empty QuerySet in django like this.

empty = classname.objects.none() 

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

class

I want the new QuerySet to have a class in it.

There is no method of adding to EmptyQuerySet and | and do not work for the db object.

+3
source share
1 answer
>>> empty = Person.objects.none()

if you use get, you return a db object and get this error when you try to use | add object to 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 | to combine two sets of queries. To get an object as a set of queries, 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>]
>>> 
+6
source

Source: https://habr.com/ru/post/1796311/


All Articles