外键查询

class AuthorInfo(models.Model):
    name = models.CharField(max_length=100)
    gender = models.CharField(max_length=100)
    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "作者表"
        verbose_name_plural = verbose_name




class BookInfo(models.Model):
    author = models.ForeignKey(AuthorInfo,related_name="zuozhe",on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    price = models.CharField(max_length=100)
    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "图书表"
        verbose_name_plural = verbose_name

from .models import AuthorInfo,BookInfo
admin.site.register(AuthorInfo)
admin.site.register(BookInfo)

  

通过外键所在表查询另外一张表的属性:

BookInfo.objects.filter().values("author__name")

通过另一张表的属性获取外键所在表的对象:

objs = BookInfo.objects.filter(author__gender="男")

 

通过外键所在表的实例,查找对应另一张表的实例:

obj = BookInfo.objects.all().first()

obj = AuthorInfo.objects.filter(zuozhe=obj).all()

 

通过外键所在表的属性,查找另一张表的对象: related_name的用处

obj = AuthorInfo.objects.filter(zuozhe__title__icontains="书").all()
for obj in obj:
print(obj.name, obj.gender)

张三 男
张三 男
小红 女
小红 女

支持去重

obj = AuthorInfo.objects.filter(zuozhe__title__icontains="书").distinct()

 支持属性去重:

obj = AuthorInfo.objects.filter(zuozhe__title__icontains="书").values("gender").distinct()
for obj in obj:
print(obj)

{'gender': '男'}
{'gender': '女'}

 

 

 

 

 

 

posted @ 2019-11-28 00:57  real-admin  阅读(1234)  评论(0编辑  收藏  举报