django 外键查询 一对多 通过对象查询和通过filter values 双下划线查询

表结构:

from django.db import models


class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.IntegerField()
    pub_date = models.DateField()
    publish = models.ForeignKey("Publish")

class Publish(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)

外键为publish

表内容:

方法一:

正向查询

是通过子表book对象取得外键pub_id的相关联的publish对象 然后通过属性查询这个publish的各种信息

from django.shortcuts import render
from .models import Book
from .models import Publish
# Create your views here.
def index(req):
    book_obj = Book.objects.get(name="python")
    pub_obj = book_obj.publish
    print(pub_obj.name)
    return render(req,"index.html")
一号出版社

方法二:

反向查询

是通过查询主表publish的对象查询相关联的书籍

from django.shortcuts import render
from .models import Book
from .models import Publish
# Create your views here.
def index(req):
    pub_obj = Publish.objects.filter(name="一号出版社")[0]
    books = pub_obj.book_set.all()
    for book in books:
        print(book.publish.name)
    return render(req,"index.html")
一号出版社
一号出版社

方法三:

先通过外键名字publish查找publish对象 找到后通过publish的name字段进行筛选

from django.shortcuts import render,HttpResponse
from .models import Book
from .models import Publish
# Create your views here.
def index(req):
    ret = Book.objects.filter(publish__name="二号出版社").values("name","price")
    #查询记录(filter values 双下划线__)
    print(ret)
    return render(req,"index.html")
<QuerySet [{'name': 'java', 'price': 22}, {'name': 'linux运维', 'price': 55}, {'name': 'linux运维2', 'price': 66}]>

查询书名为python的出版社名字

---------双下划线用在values中,切记要加引号

from django.shortcuts import render,HttpResponse
from .models import Book
from .models import Publish
# Create your views here.
def index(req):
    ret = Book.objects.filter(name="python").values("publish__name")
    #查询记录(filter values 双下划线__)
    print(ret)
    return render(req,"index.html")
<QuerySet [{'publish__name': '一号出版社'}]>

猜你喜欢

转载自blog.csdn.net/u014248032/article/details/84388039