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
object = ObjectList.objects.get(id=1)
a = CounterParty.objects.filter(object_contractor=object)
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)