对象关联查询(正向,反向)

2017-08-18  本文已影响150人  钱塘

关联查询

#coding=utf8

from django.db import models

# Create your models here.


# coding=utf8

from django.db import models


# Create your models here.


class Book(models.Model):
    title = models.CharField(max_length=64)
    price = models.IntegerField()
    color = models.CharField(max_length=64)
    page_num = models.IntegerField(null=True)
    publisher = models.ForeignKey("Publisher")     # 外键,从此处进行关联查询
    def __str__(self):
        return self.title.encode("utf-8")


class Author(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name.encode("utf-8")


# 自己写第三张表 多对多  book - author

class Book2Author(models.Model):
    author = models.ForeignKey("Author")
    book = models.ForeignKey("Book")

    # state = models.CharField(max_length=64)

    class Meta:
        unique_together = ["author","book"]  # 联合唯一


class Publisher(models.Model):
    name = models.CharField(max_length=64)
    city = models.CharField(max_length=63)    # 

    def __str__(self):
        return self.city.encode("utf-8")

正向查找:从对象按照它的属性查找

从书本《go》的publisher字段查到出版社,再通过此出版社查到出版社的地址

    ob = models.Book.objects.filter(title="go")[0]
    print(ob.publisher.city)

ob即是《go》书的出版社对象

反向查找:

    ob = models.Publisher.objects.filter(id=2)[0]
    print(ob.book_set.all().values("title"))

反向使用book_set查询,通过values查book的字段,如果需要,还可以使用distinct()去重。

上一篇下一篇

猜你喜欢

热点阅读