2

Say I have a model that is

class Bottles(models.Model) BottleCode = models.IntegerField() class Labels(models.Model) LabelCode = models.IntegerField() 

How do I get a queryset of Bottles where the BottleCode and LabelCode are equal? (i.e. Bottles and Labels with no common Code are excluded)

1
  • 1
    Be careful, your question is a clear symptom that your model is poorly designed. Commented Apr 30, 2014 at 16:20

1 Answer 1

2

It can be achieved via extra():

Bottles.objects.extra(where=["Bottles.BottleCode in (select Labels.LabelCode from Labels)"]) 

You may also need to add an app name prefix to the table names, e.g. app_bottles instead of bottles.

Though @danihp has a point here, if you would often encounter queries like these, when you are trying to relate unrelated models - you should probably think about changing your model design.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.