What is the related_name
argument useful for on ManyToManyField
and ForeignKey
fields? For example, given the following code, what is
To add to existing answer - 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
@with_author
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 = 'tomaterial')
frommaterial = models.ForeignKey(Material, related_name = 'frommaterial')
creation_time = models.DateTimeField(auto_now_add=True, blank=True)
quantity = models.DecimalField(max_digits=19, decimal_places=10)
So when you will have to access this data you only can use related name
bom = material.tomaterial.all().order_by('-creation_time')
It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)