Reputation: 7056
I am quite new to django - and I was wondering if I could use the ORM to make the below queries more efficiently:
# somewhere in views.py..
if slug is not None:
slug_field = self.get_slug_field()
pkid = FinalModel.objects.all().get(slug__exact=slug)
queryset = queryset.filter(owner__exact=pkid.id)
obj = queryset.get()
return obj
So, basically, what I am doing is (to return an object), first: get the pkid
using the slug in the url, then use this info (pkid.id
) to get the correct full object using the queryset (which operates on a different model - which is OnetToOne
keyed to the FinalModel
) statement above.
So, in a nutshell, I am first extracting the PK
using the slug
(Model=FinalModel) and use this PK
on another model (the queryset
model) which is OneToOne
keyed to the FinalModel
(using the owner
attribute).
I am not sure that using two such statements is efficient for the DB (I am no expert on this either) - and I was wondering if anyone could suggest how I could combine the two statements (pkid
and queryset
) to get the final object more efficiently.
Sorry if this is a django 101 question.
Upvotes: 0
Views: 99
Reputation: 599600
This would have been easier to answer if you'd shown your models. But assuming owner
is a ForeignKey from FinalModel to whatever model you want to get at the end, you can use the double-underscore syntax to do a JOIN:
obj = MyModel.objects.get(owner__slug=slug)
(Note you don't need to specify exact
, it's the default.)
Upvotes: 1