Django orm中related_name/related_query_name区别

class Department(models.Model):
    title = models.CharField(verbose_name='名称',max_length=32)
    
class UserInfo(models.Model):
    depart = models.ForeignKey(verbose_name='部门',to='Department')
    user = models.CharField(verbose_name='用户',max_length=32)
    pwd = models.CharField(verbose_name='密码', max_length=32)

以前查询:

正向操作:
user_object = UserInfo.objects.get(id=1)
user_object.depart

反向操作:
depart_object = Department.objects.get(id=9)
depart_object.userinfo_set.all()

使用related_query_name:

class Department(models.Model):
    title = models.CharField(verbose_name='名称',max_length=32)
    
class UserInfo(models.Model):
    depart=models.ForeignKey(verbose_name='部门',to='Department',
                             related_query_name="u")
    user = models.CharField(verbose_name='用户',max_length=32)
    pwd = models.CharField(verbose_name='密码', max_length=32)
正向操作:
	user_obj = UserInfo.object.get(id=1)
	user_obj.depart
反向操作:
	department_obj = Department.object.get(id=1)
	department_obj.u_set.all()

使用related_name:

class Department(models.Model):
    title = models.CharField(verbose_name='名称',max_length=32)
    
class UserInfo(models.Model):
    depart=models.ForeignKey(verbose_name='部门',to='Department',related_name="u")
    user = models.CharField(verbose_name='用户',max_length=32)
    pwd = models.CharField(verbose_name='密码', max_length=32)
正向操作:
	user_obj = UserInfo.object.get(id=1)
	user_obj.depart
反向操作:
	department_obj = Department.object.get(id=1)
	department_obj.u.all()

从上边的操作中可以看出这两者的区别

posted @ 2020-02-25 14:29  adrian-boy  阅读(736)  评论(0编辑  收藏  举报