1

I have 4 models in my simplified design

class modelA(models.Model):
     name = models.CharField()

class modelsUser(model.Model):
     username = models.CharField()

class bridge(models.Model):
     user = models.ForeignKey(modelUser, on_delete=models.CASCADE, related_name='bridges')
     modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='bridges')

class subModelA(models.Model):
     modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='subModelAs')
     value = models.IntegerField()

class subModelB(models.Model):
     modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='subModelBs')
     text = models.TextField()

What I am trying to to is to get all subModelBs and subModelAs that are for modelAs for which given modelUser have bridge.

I've started with this:

user = modelUser.objects.get(pk=1)
bridges = user.bridges.all()

What I've been thinking is something like this:

subModelBs = subModelB.objects.filter(modelA__in=bridges__modelA)

but unfortunately it doesn't work because of error that __modelA is not defined.

Is there any proper way to do this?

1
  • subModelBs = subModelB.objects.filter(modelA__in=user.bridges.all().values_list("modelA", flat=True))? Commented Apr 25, 2020 at 18:58

2 Answers 2

3

Find first the modelAs and then do two other queries:

modelAs = bridge.objects.filter(user__pk=1).values_list('modelA', flat=True)

subModelAs = subModelA.object.filter(modelA__in=modelAs)
subModelBs = subModelB.object.filter(modelA__in=modelAs)
Sign up to request clarification or add additional context in comments.

Comments

1

A good question first of all!

Tried reproducing on my system, the following worked for me:

user = modelUser.objects.get(pk=1)
bridges = user.bridges.all()
subModelAs = subModelA.objects.filter(
    modelA_id__in=[x.modelA_id for x in list(bridges)]
)

And similarly for subModelBs. Hope this helps you well.

Comments

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.