zoukankan      html  css  js  c++  java
  • django 外键 ,django __

    data
    
    
    
    sqlite> select * from author;
    id      name    age
    1       jim     12
    2       tom     11
    sqlite> select * from book;
    id      name    author_id
    1       learn java      1
    2       learn python    1
    3       learn c++       2
    models.py
    
    
    
    # -*- coding: UTF-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    
    # Create your models here.
    
    class Author(models.Model):
        name = models.CharField(verbose_name='姓名', max_length=50)
        age = models.IntegerField(verbose_name='年龄')
    
    class Book(models.Model):
        name = models.CharField(verbose_name='书名', max_length=100)
        author = models.ForeignKey(Author, verbose_name='作者')
    执行语句
    
    
    >>> Author.objects.filter(book__name='learn java')
    [<Author: jim>]
    >>> author = Author.objects.get(pk=1)
    >>> author.book_set.all()
    [<Book: learn java>, <Book: learn python>]
    假如把类Book改成这样
    
    
    
    class Book(models.Model):
        name = models.CharField(verbose_name='书名', max_length=100)
        author = models.ForeignKey(Author, verbose_name='作者', related_name='bs', related_query_name='b')
    那么上面查询代码就应该写成这样
    
    
    >>> Author.objects.filter(b__name='learn java')
    [<Author: jim>]
    >>> author = Author.objects.get(pk=1)
    >>> author.bs.all()
    [<Book: learn java>, <Book: learn python>]
    如果book表里有两个字段都外键关联author表,这时related_name就非常有用了。
  • 相关阅读:
    Powerdesigner数据库建模--概念模型--ER图【转】
    oralce闪回
    DBA
    linux socket使用经验总结
    寒假学习笔记1:结构化程序设计
    寒假作业2:简化电梯设计elevator
    鹤发银丝映日月,丹心热血沃新花——忆三位良师
    走廊泼水节
    种树
    P2938 [USACO09FEB]股票市场Stock Market
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/5920385.html
Copyright © 2011-2022 走看看