美文网首页
django模型中关联关系查询

django模型中关联关系查询

作者: 词穷又词贫 | 来源:发表于2017-08-18 11:30 被阅读614次

写的很乱,写的时候思路不够清晰

django中模型多对多关系

# 模型类代码
class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    class Meta:
        managed = True
        db_table = 'Blog'

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    class Meta:
        managed = True
        db_table = 'Author'

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    class Meta:
        managed = True
        db_table = 'Entry'

    def __str__(self):              # __unicode__ on Python 2
        return self.headline
ForeignKey外键约束,在django中是表示一对多的关系。
ManyToManyField 两张表建立多对多关系,本质是建立中间表关联

数据库表展示

# 形成了一张中间表Entry_authors
MariaDB [celvin]> desc Blog;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| name    | varchar(100) | NO   |     | NULL    |                |
| tagline | longtext     | NO   |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+
3 rows in set (0.02 sec)

MariaDB [celvin]> desc Author;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(50)  | NO   |     | NULL    |                |
| email | varchar(254) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

MariaDB [celvin]> desc Entry;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| headline    | varchar(255) | NO   |     | NULL    |                |
| body_text   | longtext     | NO   |     | NULL    |                |
| pub_date    | date         | NO   |     | NULL    |                |
| mod_date    | date         | NO   |     | NULL    |                |
| n_comments  | int(11)      | NO   |     | NULL    |                |
| n_pingbacks | int(11)      | NO   |     | NULL    |                |
| rating      | int(11)      | NO   |     | NULL    |                |
| blog_id     | int(11)      | NO   | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)

MariaDB [celvin]> desc Entry_authors;
+-----------+---------+------+-----+---------+----------------+
| Field     | Type    | Null | Key | Default | Extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | NO   | PRI | NULL    | auto_increment |
| entry_id  | int(11) | NO   | MUL | NULL    |                |
| author_id | int(11) | NO   | MUL | NULL    |                |
+-----------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

插入测试数据:

Blog:
insert into Blog values(1,"天龙八部","虚构");
insert into Blog values(2,"武林外传","虚构");
insert into Blog values(3,"神雕侠侣","虚构");
insert into Blog values(4,"笑傲江湖","虚构");
insert into Blog values(5,"未知世界","虚构");

Author:
insert into Author values(1,"金庸","111111111@qq.com");
insert into Author values(2,"古龙","222222222@qq.com");
insert into Author values(3,"韩寒","333333333@qq.com");

Entry:
insert into Entry values (1,"虚构","1111111111",now(),now(),1,1,1,1);
insert into Entry values (2,"虚构","2222222222",now(),now(),1,1,1,2);
insert into Entry values (3,"虚构","3333333333",now(),now(),1,1,1,3);
insert into Entry values (4,"虚构","4444444444",now(),now(),1,1,1,4);
insert into Entry values (5,"虚构","5555555555",now(),now(),1,1,1,5);

测试保存外键字段:

>>> from blog.models import Entry
>>> entry = Entry.objects.get(pk=1)
>>> cheese_blog = Blog.objects.get(name="未知世界")
>>> entry.blog = cheese_blog
>>> entry.save()

# 结果,entry中的blog外键修改,数据源自blog表中的主键,将外键字段与对象对应起来,save即可
MariaDB [celvin]> select * from Entry where id=1;
+----+----------+------------+------------+------------+------------+-------------+--------+---------+
| id | headline | body_text  | pub_date   | mod_date   | n_comments | n_pingbacks | rating | blog_id |
+----+----------+------------+------------+------------+------------+-------------+--------+---------+
|  1 | 虚构     | 1111111111 | 2017-08-17 | 2017-08-17 |          1 |           1 |      1 |       5 |
+----+----------+------------+------------+------------+------------+-------------+--------+---------+

测试保存ManyToManyField字段:
>>> entry = Entry.objects.get(pk=1)
>>> joe = Author.objects.create(name="Joe")
>>> entry.authors.add(joe)

# 结果,多对多关系中间表数据
MariaDB [celvin]> select * from Entry_authors;
+----+----------+-----------+
| id | entry_id | author_id |
+----+----------+-----------+
|  1 |        1 |         4 |
+----+----------+-----------+
# 将pk=1的entry对象关联author对象,插入到中间表中

跨关联关系的查询

# 查找entry里中blog,是未知世界的所有对象,固定写法双下斜杠,__
entrylist = Entry.objects.filter(blog__name='未知世界')

django关联关系:
一对多关联关系,两表之间是ForeignKey关系
多对多关联关系,两表之间是ManyToManyField关系,创建中间的关系表,(数据库一共三张表)

跨关联关系的查询:
# 一对多关系查询:
Entry.objects.filter(blog__name='Beatles Blog')
查询获取entry对象,条件是entry对象的外键字段blog_id与blog类且name字段为Beatles Blog的id相等
# 跨越任意深度??

# 多对多关联关系查询,使用的前提是在建立数据库模型的时候,是采用ManyToManyField的关系
enlist = Entry.objects.filter(authors__name='joe')

大写的注意:一对多关系,用类名即可,多对多关系,是用类做mangtomanyfield属性的名字

相关文章

网友评论

      本文标题:django模型中关联关系查询

      本文链接:https://www.haomeiwen.com/subject/xdzorxtx.html