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