• 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就非常有用了。
  • 相关阅读:
    Encoding
    F Takio与Blue的人生赢家之战
    D FFF团的怒火
    C Golden gun的巧克力
    B 倒不了的塔
    A jubeat
    17230 计算轴承半径
    10686 DeathGod不知道的事情
    10688 XYM-AC之路
    10692 XYM-入门之道
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/5920385.html
Copyright © 2020-2023  润新知