Philipp Chapkovski
Philipp Chapkovski

Reputation: 2059

Combine a queryset with a newly created object

There is a new object (not yet saved):

obj = MyObject()
q = MyObject.objects.all()

Is there any way to combine obj and q?

Upvotes: 0

Views: 50

Answers (2)

Satevg
Satevg

Reputation: 1601

Probably you can combine it with chain

Here I tried this in django shell:

In [1]: from itertools import chain
    ...: comment = Comment()
    ...: all_comments = Comment.objects.all()  # there's 1 comment in my db: <QuerySet [<Comment: Comment object>]>
    ...: combined = list(chain([comment], all_comments))
    ...: print(combined)
[<Comment: Comment object>, <Comment: Comment object>]

Upvotes: 1

ruddra
ruddra

Reputation: 51948

You can't combine if the obj is not saved(assuming you want to use the queryset here). here q is a lazy query. When it is evaluated, then it will bring all the objects including obj if its created before evaluation.

But You can append it to the list of objects after the q is evaluated(if you don't want to save obj no matter what). Like this:

q_list = list(q)
q_list.append(obj)

Upvotes: 0

Related Questions