系统的了解DJANGO中数据MODULES的相关性引用

数据库结构如下:

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

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

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

    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()

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

终于对这个东东有个系统性的了解了。

真正要用时,还是要查一查的。。

Related objects

When you define a relationship in a model (i.e., a ForeignKeyOneToOneField, or ManyToManyField), instances of that model will have a convenient API to access the related object(s).

Using the models at the top of this page, for example, an Entry object e can get its associated Blog object by accessing the blogattribute: e.blog.

(Behind the scenes, this functionality is implemented by Python descriptors. This shouldn’t really matter to you, but we point it out here for the curious.)

Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Blog object b has access to a list of all related Entry objects via the entry_set attribute:b.entry_set.all().

All examples in this section use the sample BlogAuthor and Entry models defined at the top of this page.

One-to-many relationships

Forward

If a model has a ForeignKey, instances of that model will have access to the related (foreign) object via a simple attribute of the model.

Example:

>>> e = Entry.objects.get(id=2)
>>> e.blog # Returns the related Blog object.

You can get and set via a foreign-key attribute. As you may expect, changes to the foreign key aren’t saved to the database until you callsave(). Example:

>>> e = Entry.objects.get(id=2)
>>> e.blog = some_blog
>>> e.save()

If a ForeignKey field has null=True set (i.e., it allows NULL values), you can assign None to remove the relation. Example:

>>> e = Entry.objects.get(id=2)
>>> e.blog = None
>>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"

Forward access to one-to-many relationships is cached the first time the related object is accessed. Subsequent accesses to the foreign key on the same object instance are cached. Example:

>>> e = Entry.objects.get(id=2)
>>> print(e.blog)  # Hits the database to retrieve the associated Blog.
>>> print(e.blog)  # Doesn‘t hit the database; uses cached version.

Note that the select_related() QuerySet method recursively prepopulates the cache of all one-to-many relationships ahead of time. Example:

>>> e = Entry.objects.select_related().get(id=2)
>>> print(e.blog)  # Doesn‘t hit the database; uses cached version.
>>> print(e.blog)  # Doesn‘t hit the database; uses cached version.

Following relationships “backward”

If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated as described in the “Retrieving objects” section above.

Example:

>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.

# b.entry_set is a Manager that returns QuerySets.
>>> b.entry_set.filter(headline__contains=‘Lennon‘)
>>> b.entry_set.count()

You can override the FOO_set name by setting the related_name parameter in the ForeignKey definition. For example, if the Entrymodel was altered to blog = ForeignKey(Blog, related_name=‘entries‘), the above example code would look like this:

>>> b = Blog.objects.get(id=1)
>>> b.entries.all() # Returns all Entry objects related to Blog.

# b.entries is a Manager that returns QuerySets.
>>> b.entries.filter(headline__contains=‘Lennon‘)
>>> b.entries.count()

Using a custom reverse manager

New in Django 1.7.

By default the RelatedManager used for reverse relations is a subclass of the default manager for that model. If you would like to specify a different manager for a given query you can use the following syntax:

from django.db import models

class Entry(models.Model):
    #...
    objects = models.Manager()  # Default Manager
    entries = EntryManager()    # Custom Manager

b = Blog.objects.get(id=1)
b.entry_set(manager=‘entries‘).all()

If EntryManager performed default filtering in its get_queryset() method, that filtering would apply to the all() call.

Of course, specifying a custom reverse manager also enables you to call its custom methods:

b.entry_set(manager=‘entries‘).is_published()

Additional methods to handle related objects

In addition to the QuerySet methods defined in “Retrieving objects” above, the ForeignKey Manager has additional methods used to handle the set of related objects. A synopsis of each is below, and complete details can be found in the related objects reference.

add(obj1, obj2, ...)
Adds the specified model objects to the related object set.
create(**kwargs)
Creates a new object, saves it and puts it in the related object set. Returns the newly created object.
remove(obj1, obj2, ...)
Removes the specified model objects from the related object set.
clear()
Removes all objects from the related object set.

To assign the members of a related set in one fell swoop, just assign to it from any iterable object. The iterable can contain object instances, or just a list of primary key values. For example:

b = Blog.objects.get(id=1)
b.entry_set = [e1, e2]

In this example, e1 and e2 can be full Entry instances, or integer primary key values.

If the clear() method is available, any pre-existing objects will be removed from the entry_set before all objects in the iterable (in this case, a list) are added to the set. If the clear() method is not available, all objects in the iterable will be added without removing any existing elements.

Each “reverse” operation described in this section has an immediate effect on the database. Every addition, creation and deletion is immediately and automatically saved to the database.

Many-to-many relationships

Both ends of a many-to-many relationship get automatic API access to the other end. The API works just as a “backward” one-to-many relationship, above.

The only difference is in the attribute naming: The model that defines the ManyToManyField uses the attribute name of that field itself, whereas the “reverse” model uses the lowercased model name of the original model, plus ‘_set‘ (just like reverse one-to-many relationships).

An example makes this easier to understand:

e = Entry.objects.get(id=3)
e.authors.all() # Returns all Author objects for this Entry.
e.authors.count()
e.authors.filter(name__contains=‘John‘)

a = Author.objects.get(id=5)
a.entry_set.all() # Returns all Entry objects for this Author.

Like ForeignKeyManyToManyField can specify related_name. In the above example, if the ManyToManyField in Entry had specified related_name=‘entries‘, then each Author instance would have an entries attribute instead of entry_set.

One-to-one relationships

One-to-one relationships are very similar to many-to-one relationships. If you define a OneToOneField on your model, instances of that model will have access to the related object via a simple attribute of the model.

For example:

class EntryDetail(models.Model):
    entry = models.OneToOneField(Entry)
    details = models.TextField()

ed = EntryDetail.objects.get(id=2)
ed.entry # Returns the related Entry object.

The difference comes in “reverse” queries. The related model in a one-to-one relationship also has access to a Manager object, but thatManager represents a single object, rather than a collection of objects:

e = Entry.objects.get(id=2)
e.entrydetail # returns the related EntryDetail object

If no object has been assigned to this relationship, Django will raise a DoesNotExist exception.

Instances can be assigned to the reverse relationship in the same way as you would assign the forward relationship:

e.entrydetail = ed

How are the backward relationships possible?

Other object-relational mappers require you to define relationships on both sides. The Django developers believe this is a violation of the DRY (Don’t Repeat Yourself) principle, so Django only requires you to define the relationship on one end.

But how is this possible, given that a model class doesn’t know which other model classes are related to it until those other model classes are loaded?

The answer lies in the app registry. When Django starts, it imports each application listed in INSTALLED_APPS, and then the modelsmodule inside each application. Whenever a new model class is created, Django adds backward-relationships to any related models. If the related models haven’t been imported yet, Django keeps tracks of the relationships and adds them when the related models eventually are imported.

For this reason, it’s particularly important that all the models you’re using be defined in applications listed in INSTALLED_APPS. Otherwise, backwards relations may not work properly.

时间: 2024-12-14 10:12:23

系统的了解DJANGO中数据MODULES的相关性引用的相关文章

django中数据查找条件是表中的外键对应表的列该如何查找?

1 平常查找表中数据的条件是python中已有的数据类型,通过点运算符可以直接查找.如果条件是表中外键列所对应表的某一列,该如何查询数据?比如 class News(models.Model): title = models.CharField(max_length=50); summary = models.TextField(); url = models.CharField(max_length=150); favorCount = models.IntegerField(default=

Django中的数据记录的增、删、改、查

Django中数据的增删改查操作如下: 我们以一个model:User为例,User有三个字段,一个是username.passwd.phonenumber (1)增加一条记录 添加一个username.passwd.phonenumber字段值为s_username.s_passwd.s_phonenumber的记录 user=User() user.username=s_username user.passwd=s_passwd user.phonenumber=s_phonenumber

Django中如何将数据库的数据展示在网页上

Django中数据展示需要由视图.模型和模板共同实现,实现步骤如下: 定义数据模型,以类的方式定义数据表的字段.在数据库创建数据表时,数据表由模型中定义的类生成: 在视图中导入模型所定义的类,该类也称为数据表对象,Django为数据表对象提供独有的数据操作方法ORM,可以实现数据库操作,从而获取数据表数据: 视图函数获取数据后,将数据以字典.列表或对象的方式传入给HTML模板,并由模板引擎接收和解析,最后生成相应的HTML网页. 用户的请求信息都放在视图函数的参数request中,其中属性GET

Django模板系统(非常详细)(后台数据如何展示在前台)

前面的章节我们看到如何在视图中返回HTML,但是HTML是硬编码在Python代码中的这会导致几个问题:1,显然,任何页面的改动会牵扯到Python代码的改动网站的设计改动会比Python代码改动更频繁,所以如果我们将两者分离开会更方便2,其次,写后台Python代码与设计HTML是不同的工作,更专业的Web开发应该将两者分开页面设计者和HTML/CSS程序员不应该编辑Python代码,他们应该与HTML打交道3,程序员写Python代码同时页面设计者写HTML模板会更高效,而不是一个人等待另一

Django中使用Json返回数据

在一个网站在,大量数据与前端交互,JSON是最好的传递数据方式了. 在Django中,使用JSON传输数据,有两种方式,一种是使用Python的JSON包,一种是使用Django的JsonResponse 方法一:使用Python的JSON包 1 from django.shortcuts import HttpResponse 2 3 import json 4 5 6 def testjson(request): 7 data={ 8 'patient_name': '张三', 9 'age

Django model中数据批量导入bulk_create()

在Django中需要向数据库中插入多条数据(list).使用如下方法,每次save()的时候都会访问一次数据库.导致性能问题: for i in resultlist: p = Account(name=i) p.save() 在django1.4以后加入了新的特性.使用django.db.models.query.QuerySet.bulk_create()批量创建对象,减少SQL查询次数.改进如下: querysetlist=[] for i in resultlist: querysetl

Django 中的用户认证

Django 自带一个用户认证系统,这个系统处理用户帐户.组.权限和基于 cookie 的 会话.本文说明这个系统是如何工作的. 概览 认证系统由以下部分组成: 用户 权限:控制用户进否可以执行某项任务的二进制(是/否)标志. 组:一种为多个用户加上标签和权限的常用方式. 消息:一种为指定用户生成简单消息队列的方式. Deprecated in Django 1.2: 认证系统的消息部分将会在 Django 1.4 版中去除. 安装 认证系统打包在 Django 的 django.contrib

django中的事务管理

在讲解之前首先来了解一下数据库中的事务. 什么是数据库中的事务? 热心网友回答: (1):事务(Transaction)是并发控制的单位,是用户定义的一个操作序列.这些操作要么都做,要么都不做,是一个不可分割的工作单位.通过事务,SQL Server能将逻辑相关的一组操作绑定在一起,以便服务器保持数据的完整性. (2):事务通常是以BEGIN TRANSACTION开始,以COMMIT或ROLLBACK结束. COMMIT表示提交,即提交事务的所有操作.具体地说就是将事务中所有对数据库的更新写回

Django中如何使用django-celery完成异步任务

本篇博文主要介绍在开发环境中的celery使用,请勿用于部署服务器. 许多Django应用需要执行异步任务, 以便不耽误http request的执行. 我们也可以选择许多方法来完成异步任务, 使用Celery是一个比较好的选择, 因为Celery有着大量的社区支持, 能够完美的扩展, 和Django结合的也很好. Celery不仅能在Django中使用, 还能在其他地方被大量的使用. 因此一旦学会使用Celery, 我们可以很方便的在其他项目中使用它. 1. Celery版本 本篇博文主要针对