0

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.

1 Answer 1

1

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much for this - that works perfectly!! I was wondering if I could ask you another question (probably not completely related to this). I was wondering what this statement does: queryset = queryset.filter(**{slug_field: slug}) especially, what does **{slug_field: slug} construct mean here? Thanks so much for all your help - has certainly helped me understand better.
**dict is just a means of passing a dictionary as keyword arguments. That's useful because the keyword name itself can be a variable, as in your example, as well as the value.
Thanks a tonne. Solved all problems :) Marked your answer as correct!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.