What is `related_name` used for in Django?

前端 未结 6 1364
长发绾君心
长发绾君心 2020-11-22 03:53

What is the related_name argument useful for on ManyToManyField and ForeignKey fields? For example, given the following code, what is

6条回答
  •  醉话见心
    2020-11-22 04:21

    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.)

提交回复
热议问题