related_name/related_query_name 一般出现在有 Foreignkey 或者 Manytomang 字段的时候
一 一般查询
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 反向查询---表名小写+set 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_object = UserInfo.objects.get(id=1) user_object.depart 反向查询---表名小写+set depart_object = Department.objects.get(id=9) depart_object.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_object = UserInfo.objects.get(id=1) user_object.depart 反向查询---表名小写+set depart_object = Department.objects.get(id=9) depart_object.u.all()