Django Fields Related_Name Django.How

Author avatar wrote on 08/06/2022

Related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material


class BOM(models.Model): 
    name = models.CharField(max_length=200,null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tomaterial =  models.ForeignKey(Material, related_name = 'tomaterials')
    frommaterial =  models.ForeignKey(Material, related_name = 'frommaterials')

So when you will have to access this data you only can use related name

bom = material.tomaterial.all().order_by('-creation_time')


# if you add the +, django disables the mapping 
rommaterial =  models.ForeignKey(Material, related_name = '+')

# related_name should be plural. Because ForeignKey relations return multiple objects.