Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an model instance to a django queryset?

Tags:

python

django

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:

from my_django_app.models import MyModel  queryset = MyModel.objects.none() queryset.append(MyModel.objects.first())      ## no list's .append() method! 

Is there any way to add an model instance to an existing queryset?

like image 236
June Avatar asked Apr 12 '15 08:04

June


People also ask

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.


1 Answers

You can also use the | operator to create a union:

queryset = MyModel.objects.none() instance = MyModel.objects.first() queryset |= MyModel.objects.filter(pk=instance.pk) 

But be warned that this will generate different queries depending on the number of items you append this way, making caching of compiled queries inefficient.

like image 59
Feuermurmel Avatar answered Sep 16 '22 12:09

Feuermurmel