What is `related_name` used for in Django?

前端 未结 6 1361
长发绾君心
长发绾君心 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:14

    The related_name argument is also useful if you have more complex related class names. For example, if you have a foreign key relationship:

    class UserMapDataFrame(models.Model):
        user = models.ForeignKey(User) 
    

    In order to access UserMapDataFrame objects from the related User, the default call would be User.usermapdataframe_set.all(), which it is quite difficult to read.

    Using the related_name allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specify user = models.ForeignKey(User, related_name='map_data'), the call would then be User.map_data.all().

提交回复
热议问题