[Answered ]-Queryset containing related Object with same foreignkey

1👍

You can obtain the Places of a Persons object with:

Places.object.filter(adress__persons=myperson)

If you want to do this in bulk, you can work with:

qs = Persons.objects.select_related('adress').prefetch_related('adress__places_set')

this will load the related Places in bulk, so you can fetch these with:

for person in qs:
    print(person.adress.places_set.all())

0👍

You can do somethings like this but first you need to add related_name in your Persons and Places Foreign key

class Persons(models.Model):
     adress = models.ForeignKey(Adress,related_name = "persons_adress",on_delete=models.DO_NOTHING, blank=True,null=True)
class Adress(models.Model):
     some_data = models.IntegerField()
class Places(models.Model):
     adress = models.ForeignKey(Adress, related_name = "places_addres",on_delete=models.DO_NOTHING)

After this alteration you can now query

Adress.objects.filter(persons_adress__some_data = some_data,places_addres__some_data = some_data)

Leave a comment