Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter one model by another if it doesnt have relation

I have 2 models and model ObjectList has m2m field to CounterParty but i need to show info from CounterParty model filtered by object

How am i suppose to do it?

class CounterParty(models.Model):
    name = models.CharField(max_length=150, verbose_name='Наименование')


class ObjectList(models.Model):

    name = models.CharField(max_length=250, verbose_name='Наименование')

    contractor_guid = models.ManyToManyField(CounterParty, related_name='object_contractor',default=None, blank=True)

I know this is not right but it should look like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

object = ObjectList.objects.get(id=1)
a = CounterParty.objects.filter(object_contractor=object)

>Solution :

Your attempt is correct: you use the related_name to query in reverse. The fact that it is not defined on the model is not relevant: queries can be done in all directions. If you however don’t need the ObjectList, you can just use:

CounterParty.objects.filter(object_contractor__id=1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading