注意Django的生成的默认api

from django.db import models

class Place(models.Model):
'''
  pass class Restaurant(models.Model):
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
primary_key=True,
)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False) def __str__(self): # __unicode__ on Python 2
return "%s the restaurant" % self.place.name class Waiter(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
name = models.CharField(max_length=50) def __str__(self): # __unicode__ on Python 2
return "%s the waiter at %s" % (self.name, self.restaurant)

place_instance.restaurant 引用对应的 restaurant,为 Model `Restaurant`名称的 lower() 形式

restaurant.place,通过字段名称 `place` 引用


restaurant_instance.waiter_set 与 restaurant_instance.waiter 有什么不同?

现在发现时有 Manytomany 的一边引用另一个 model,不需要加 _set,反之,需要加 _set。两者都是相互引用的名称,没有区别

related_name 中可以定义这个名称,在 Manytomany 中两边的名称分别是什么?

django 官方教程

Django OneToOneField, ManyToManyField, Foreign Key

Imagine a database, which stores your book collection:

from django.db import models

class Place(models.Model):
address = models.CharField(max_length=50)
country = models.CharField(max_length=50) class Publisher(models.Model):
name = models.CharField(max_length=30)
place = models.OneToOneField(Place, primary_key=True) class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40) class Book(models.Model):
title = models.CharField(max_length=100)
publisher = models.ForeignKey(Publisher)
authors = models.ManyToManyField(Author)

One-to-many/Foreign Key  

Every Book has one Publisher, but a Publisher might have published multiple books. Therefore they are in a one-to-many (book-to-publisher) relationship. So,

class Book(models.Model):
    publisher = models.ForeignKey(Publisher, realted_name='books')

should be read: "Book is the foreign key of publisher". `publisher` is a attribute of book, a book only has one publisher, `book.publisher` is a instance of `Publisher`.

`publisher` can access books by related_name `books`, `publisher.books` is a queryset of `Book`.

外键是 one to many 中 many 的一方, related_name 是 Publisher 访问 Book 的名称,是单获取多的名字。

外键的自联接

class City(BaseModel):
'''
城市
'''
name = models.CharField(max_length=64, verbose_name='名称')
# 从1开始
level = models.SmallIntegerField(null=True, blank=True, verbose_name='级别')
search_count = models.IntegerField(default=0, verbose_name="搜索次数")
upper_city = models.ForeignKey('self', related_name='sub_cities', on_delete=models.CASCADE)

以国家--省--市的级别。

如广东省

广东省.upper_city = 中国
广东省.sub_cities = City Queryset [广州、深圳、珠海]

  

One-to-one

Every Publisher is located in one Place, and every Place can only hold one Publisher. Therefore they are in a one-to-one relationship. You could just have well have put the Place information (address and country) with the Publisher model in one table, but sometimes it is preferred to have seperate models. For example, if you do not know the Place for every Publisher, you don't need to take up a lot of space with empty rows.

Many-to-many

Every Book also has one or more Authors. However, an Author might have written multiple Books, so they are in a many-to-many relationship.

If you still need some guidance, I suggest taking a look at the model chapter of the Django Book.

The apis of different relations

base apis

manytomany

Related objects reference

add

remove

clear 等等

问:Related objects reference 中的方法是怎么实现的?

首先要弄懂 Foreignkey 的方法是怎么实现的

问:弄懂 Foreignkey 的方法是怎么实现的

 1. 两个 models 之间如何相互引用的?

2. 增删查改

问:intermediary model

如何通过 intermediary model 取出数据?

通过对应的字段 id 取出,见 Associative_entity

intermediary model 的作用

可以用来储存关系之外的信息,比如这个关系的建立日期,建立条件等

用来取到不同的值,比如默认是取 pk,但是现在能取到 username

遇到的问题

AttributeError}Cannot set values on a ManyToManyField which specifies an intermediary model.

原因:many2many 自带的 api 不再适用

Unlike normal many-to-many fields, you can't use add, create, or assignment (i.e., beatles.members = [...]) to create relationships

解决:

在中间表加上

class Membership(models.Model):
class Meta:
auto_created = True

来源

 问:Django 自带的 ManyToManyField 是如何实现的,有没有使用 intermediary model

搜索了一下,没有找到满意的答案。于是查看添加 ManyToManyField 后的 sql 语句。

下面是将一个 CharField 改为 ManyToManyField 后,Django 生成的 sql 语句

app_name: business, related_model_name: Client, Industry

BEGIN;
--
-- Remove field industry from client
--
ALTER TABLE `business_client` DROP COLUMN `industry` CASCADE;
--
-- Add field industry to client
--
CREATE TABLE `business_client_industry` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `client_id` integer NOT NULL, `industry_id` integer NOT NULL);
ALTER TABLE `business_client_industry` ADD CONSTRAINT `business_client_industr_client_id_0cf3c644_fk_business_client_id` FOREIGN KEY (`client_id`) REFERENCES `business_client` (`id`);
ALTER TABLE `business_client_industry` ADD CONSTRAINT `business_client_ind_industry_id_4e2c4fda_fk_business_industry_id` FOREIGN KEY (`industry_id`) REFERENCES `business_industry` (`id`);
ALTER TABLE `business_client_industry` ADD CONSTRAINT `business_client_industry_client_id_06a60532_uniq` UNIQUE (`client_id`, `industry_id`); COMMIT;

从上面可以看出:

1. ManyToManyField 也生成了一个中间表 CREATE TABLE `business_client_industry`

2. 在中间表中创建外键

3. 自动增加了一个 UNQUE 约束

问:为什么使用 intermediary model时不能使用 clear 之外的方法?

既然同样都是通过中间表引用,为什么到了这里那些方法就不能用了呢?

实际测试一下再来作答

因为要建立联系,必须要在中间表中建立数据。而 clear 之外的那些方法做不到。

You can’t just create a relationship between a Person and a Group - you need to specify all the detail for the relationship required by the Membership model. The simple addcreate and assignment calls don’t provide a way to specify this extra detail. As a result, they are disabled for many-to-many relationships that use an intermediate model. The only way to create this type of relationship is to create instances of the intermediate model.

 clear 为什么能做到?

clear 是将那个属性设置为  None,只是破坏单边关系吧?为什么说破坏了 many to many relationship?

是不是一边为空就会破坏 many to many 的关系?

问:如何做城市选择?

服务端如何做国内外选择城市功能

问:Django model循环引用

解决:http://stackoverflow.com/questions/4813293/django-python-circular-model-reference

原理: 懒加载

django database relations的更多相关文章

  1. Django中如何配置Database缓存?

    BACKEND: django.core.cache.backends.db.DatabaseCache LOCATION: 数据库表名 示例: CACHES = { 'default': { 'BA ...

  2. Django中如何使用django-celery完成异步任务1(转)

    原文链接: http://www.weiguda.com/blog/73/ 本篇博文主要介绍在开发环境中的celery使用,请勿用于部署服务器. 许多Django应用需要执行异步任务, 以便不耽误ht ...

  3. Django使用manage.py备份与恢复数据

    Django dumpdata and loaddata django database model dumpdata dumpdata command It is a django manageme ...

  4. Django学习笔记之使用 Django项目开发框架

    Django 项目是一个定制框架,它源自一个在线新闻 Web 站点,于 2005 年以开源的形式被释放出来.Django 框架的核心组件有: 用于创建模型的对象关系映射 为最终用户设计的完美管理界面 ...

  5. Django 初始化数据库

    django 初始化数据库 刷新数据库guoguos-MacBook-Pro:mysite guoguo$ python manage.py sqlflushBEGIN;SET FOREIGN_KEY ...

  6. Celery 分布式任务队列快速入门

    Celery 分布式任务队列快速入门 本节内容 Celery介绍和基本使用 在项目中如何使用celery 启用多个workers Celery 定时任务 与django结合 通过django配置cel ...

  7. UML类图中箭头的含义

    Explanation of the UML arrows Here's some explanations from the Visual Studio 2015 docs: UML Class D ...

  8. Professional C# 6 and .NET Core 1.0 - Chapter 42 ASP.NET Web API

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处: -------------------------------------------------------- ...

  9. 【转】Celery 分布式任务队列快速入门

    Celery 分布式任务队列快速入门 本节内容 Celery介绍和基本使用 在项目中如何使用celery 启用多个workers Celery 分布式 Celery 定时任务 与django结合 通过 ...

随机推荐

  1. XYWi-Fi v2.0 简单的笔记本无线热点分享工具【Win】

    [软件名称]XYWi-Fi [版本号]v2.0 [适用系统]Windows 7/8/8.1/10 [功能特性]简单的笔记本无线热点分享工具 [下载地址]pan.baidu.com/s/1mgmOpJi ...

  2. Android.KungFu手机病毒原理及清理方法

    原文链接:http://jingyan.baidu.com/article/363872ec8ad56b6e4ba16fb1.html Android.KungFu手机病毒清理方法 浏览:3333 | ...

  3. nginx中ngx_list的数据结构

    今天没事了,在查看nginx源代码中看到ngx_list的结构,发现设计为链表数组的形式,不知道为什么这样设计 struct ngx_list_part_s { void *elts;//指向数组的起 ...

  4. 生产环境中 Ngx_lua 使用技巧和应用的范例

    生产环境中 Ngx_lua 使用技巧和应用的范例 时间 -- :: 51CTO技术博客 原文 http://rfyiamcool.blog.51cto.com/1030776/1252501 主题 L ...

  5. 关于linux系统下 无法解析主机的问题

    linux无法解析主机 xxx: 解决方法: 1. sudo gedit /etc/hosts 找到如下行: 127.0.1.1       XXX 将其修改为: 127.0.1.1       (你 ...

  6. leetCode 75.Sort Colors (颜色排序) 解题思路和方法

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

  7. driver基础

    驱动测试时,linux驱动常以模块方式插入内核.应包含头文件:linux/kernel.h,linux/module.h 设备驱动的一般结构:Soc(主芯片->设备控制器->外设引脚)-- ...

  8. Problem #3263 丽娃河的狼人传说 区间满足灯数,r排序后贪心。

    丽娃河的狼人传说 Time limit per test: 1.0 seconds Time limit all tests: 1.0 seconds Memory limit: megabytes ...

  9. hdu2588 GCD 给定n,m。求x属于[1,n]。有多少个x满足gcd(x,n)>=m; 容斥或者欧拉函数

    GCD Time Limit: / MS (Java/Others) Memory Limit: / K (Java/Others) Total Submission(s): Accepted Sub ...

  10. dp解Codeforces Round #260 (Div. 2)C. Boredom

    #include<iostream> #include<map> #include<string> #include<cstring> #include ...