Django What is reverse relationship?

后端 未结 2 1690
旧时难觅i
旧时难觅i 2020-11-28 05:59

Can someone tell me what is reverse relationship means? I have started using Django and in lot of places in the documentation I see \'reverse relationship, being mentioned.

相关标签:
2条回答
  • 2020-11-28 06:19

    Here is the documentation on related_name

    Lets say you have 2 models

    class Group(models.Model):
        #some attributes
    
    class Profile(models.Model):
        group = models.ForeignKey(Group)
        #more attributes
    

    Now, from a profile object, you can do profile.group. But if you want the profile objects given the group object, How would you do that? Thats' where related name or the reverse relationship comes in.

    Django, by defaults gives you a default related_name which is the ModelName (in lowercase) followed by _set - In this case, It would be profile_set, so group.profile_set.

    However, you can override it by specifying a related_name in the ForeignKey field.

    class Profile(models.Model):
        group = models.ForeignKey(Group, related_name='profiles')
        #more attributes
    

    Now, you can access the foreign key as follows:

    group.profiles.all()
    
    0 讨论(0)
  • 2020-11-28 06:31

    In Django 2.0 you would define a ForeignKey as follows

    mainclient = models.ForeignKey( MainClient, on_delete=model.CASCADE, related_name='+')  
    

    the related_name='+' would cancel the default reverse relationship that Django sets up, so in the previous example, you would not be able to query the profiles using group.profiles.all().

    0 讨论(0)
提交回复
热议问题