24、related_namerelated_query_name 的区别

related_name/related_query_name 的区别

related_name/related_query_name 一般出现在有 Foreignkey 或者 ManyToManyField 字段的时候

一般查询

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

Last updated