Reputation: 15685
The django docs have the following:
entry = Entry.objects.get(pk=123)
if some_queryset.filter(pk=entry.pk).exists():
print("Entry contained in queryset")
could someone explain how this works? does the first line have to be executed? can we just do:
if some_queryset.filter(pk=123).exists():
print("Entry contained in queryset")
I'm confused by what some_queryset is. In the above example wouldn't:
entry = Entry.objects.get(pk=123)
if entry.filter(pk=entry.pk).exists():
print("Entry contained in queryset")
make more sense?
Upvotes: 0
Views: 2668
Reputation: 476729
can we just do:
if some_queryset.filter(pk=123).exists(): print("Entry contained in queryset")
Yes. The Django documentation only uses the example to fetch the Entry
first to demonstrate that the Entry
with pk=123
exists in the Entry
records. If you then want to check if it also exists in the some_queryset
(which is for example a .filter(…)
ed version of Entry.objects.all()
), you can work with .filter(pk=entry.pk)
.
But you do not need to fetch the Entry
object first, if you somehow know the primary key in advance, you can already work with it directly. After all entry.pk
is simply 123
, and it does not matter what the origin of that data is for the .filter()
clause.
I'm confused by what some_queryset is.
The idea is that they here have a some_queryset
, which is a QuerySet
over Entry
objects. This can for example be an Entry.objects.filter(pub_date__year=2010)
, so a queryset that is filtered. If you then want to know if the entry
is a member of this filtered queryset, you can use some_queryset.filter(pk=123).exists()
to check if an Entry
with pk=123
is a member of this queryset. In this specific case (with pub_date__year=2010
), we thus check if that Entry
belongs to Entry
s published in 2010.
Upvotes: 1