Home > Blockchain >  Queryset containing related Object with same foreignkey
Queryset containing related Object with same foreignkey

Time:10-27

e.g. I've a person with an address

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

and i have another related data in antoher model like this

class Places(models.Model):
adress = models.ForeignKey(Adress, on_delete=models.DO_NOTHING)

how can i get a queryset now of both persons and places if adress is set in persons?

CodePudding user response:

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

CodePudding user response:

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)
  • Related