I am trying to call the list of M2M
objects referenced in ModelB
from ModelC
.
I normally use it the other way around (start with parent model and filter down to child), but this time I cant see a way around it.
I feel there might be something to do with the related name, but the behaviour seems different than with normal FK.
I tried different options. The most commonly suggested is to use _set.all
which I cant seem to make work.
class ModelA(models.Model):
title = models.CharField(verbose_name="title",max_length=100, null=True, blank=True)
class ModelB(models.Model):
ModelB_Field1= models.ManyToManyField(ModelA, blank=True)
class ModelC(models.Model):
ModelC_Field1= models.ForeignKey(ModelB,null=True, blank=True, on_delete=models.SET_NULL, related_name='modelc_field1')
def function(request, modelc_id):
q = ModelC.objects.get(pk=modelc_id).modelC_field1_set.all()
Doing this gives the following error: :'ModelC' object has no attribute 'ModelC_Field1_set'
How can I access all the objects in m2m field in ModelB model from ModelC?