django orm

Posted zhulibin2012

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django orm相关的知识,希望对你有一定的参考价值。

1.正查询和反查

从有外键关联的表中查询没有外键的表 ---正查询; 反之反查询.比如如下字段:

class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    email = models.CharField(max_length=32)
    ad = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    address = models.CharField(max_length=32)
    telephone = models.IntegerField()

使用author对象查询AuthorDetail对象信息,则是正查. 反之反查询

正查询: 如下: ad指AuthorDetail对象

author = Author.objects.get(id=1)
author.name
金庸
author.ad.address
香港

反查询: 因为AuthorDetail没有记录Author表的关联属性,所以直接使用类名小写.

author_adress=AuthorDetail.objects.get(id=1)
author_adress.author
<Author: Author object (1)>
author_adress.author.name
金庸

反查询

方式一: 对象.类名_set.all()

class Article: tags = models.ManyToManyField(Tags, blank=True)

class Tags(models.Model):
    """
     标签 Tag 也比较简单,和 Category 一样。
     再次强调一定要继承 models.Model 类!
     """
    name = models.CharField(标签, max_length=100)

 

反查询即从Tags查询Article对象信息:

tags = Tags.objects.get(id=1)
out:<Tags: java标签1>
tags.article_set
out:<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x00000157FF7B16A0>
tags.article_set.get(id=1)
out: <Article: java基础>

方式二:使用使用relate_name

related_name=‘publisher‘

# 验证查询操作
class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32, default=None)
    create_time = models.DateTimeField(auto_now=True)
    price = models.DecimalField(decimal_places=2, max_digits=8, default=None)
    publisher = models.ForeignKey(to="Publish", on_delete=models.CASCADE,related_name=publisher)
    authors = models.ManyToManyField(to=Author,null=True,related_name=authors)
    reader=models.CharField(max_length=12,null=True)

    def __str__(self):
        return str(self.nid) + : + self.title


class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    email = models.CharField(max_length=32)

则反查询值:

 

p = Publish.objects.get(nid=1)
p.name
北京文化
p.publisher.all()
<QuerySet [<Book: 1:book_0>, <Book: 2:book_1>, <Book: 3:book_2>, <Book: 4:book_3>, <Book: 5:book_4>, <Book: 6:book_5>, <Book: 7:book_6>, <Book: 8:book_7>, <Book: 9:book_8>, <Book: 10:book_9>, <Book: 11:book_10>, <Book: 12:book_11>, <Book: 13:book_12>, <Book: 14:book_13>, <Book: 15:book_14>, <Book: 16:book_15>, <Book: 17:book_16>, <Book: 18:book_17>, <Book: 19:book_18>, <Book: 20:book_19>, ...(remaining elements truncated)...]>

 

 

 

 

以上是关于django orm的主要内容,如果未能解决你的问题,请参考以下文章

Django之ORM操作

Django orm的使用

Django---ORM操作大全

Django models ORM基础操作--白话聊Django系列

Django之ORM

Django-ORM操作数据库无数据问题