08.15 self-summary
About creating relationships between different forms of django
A. Create a relationship between the different
1. One to One
For example
母表:userinfo
id | name | age |
---|---|---|
1 | Joe Smith | 12 |
2 | John Doe | 58 |
Word table: private
id | salary | sp_id |
---|---|---|
1 | 100 | 1 |
2 | 400 | 2 |
models.py
class UserInfo(models.Model):
name = models.CharField(max_length=32, null=True)
age = models.IntegerField(null=True)
class Private(models.Model):
salary = models.CharField(max_length=32, null=True)
sp = models.OneToOneField("UserInfo", null=True) #oneTooneField: 一对一, 默认要求该字段必须是唯一的 unique 外键关系
Insert information
models.UserInfo.objects.create(name='张三',age=12)
models.Private.objects.create(salary=100,sp_id=1)
Inquire
#从母表查询子表中的数据
#方法1:res = models.UserInfo.objects.filter(name='张三').first().private.salary #子表表名小写.子表字段名
#方法2:res = models.UserInfo.objects.filter(name='张三').values('private__salary')
#从子表查询母表信息
#方法1:res = models.Private.objects.filter(salary='100').first().sp.name
#方法2:res = models.Private.objects.values('sp__name'):
2. to-many (by table)
models.py
class Boy(models.Model):
bname = models.CharField(max_length=30,null=True)
class Girl(models.Model):
gname = models.CharField(max_length=30,null=True)
class Boy2Girl(models.Model):
b = models.ForeignKey('Boy',null=True)
g = models.ForeignKey('Girl',null=True)
#联合唯一属性
class Meta:
unique_together=[
('b','g')
]
Insert information
import random
boys =[
models.Boy(bname='男1'),
models.Boy(bname='男2'),
models.Boy(bname='男3'),
models.Boy(bname='男4'),
models.Boy(bname='男5'),
models.Boy(bname='男6')
]
res = models.Boy.objects.bulk_create(boys)
girls =[
models.Girl(gname='女1'),
models.Girl(gname='女2'),
models.Girl(gname='女3'),
models.Girl(gname='女4'),
models.Girl(gname='女5'),
models.Girl(gname='女6'),
models.Girl(gname='女7'),
models.Girl(gname='女8'),
]
models.Girl.objects.bulk_create(girls)
a = [
models.Boy2Girl(b_id=random.randint(1,6),g_id=1),
models.Boy2Girl(b_id=random.randint(1,6),g_id=2),
models.Boy2Girl(b_id=random.randint(1,6),g_id=3),
models.Boy2Girl(b_id=random.randint(1,6),g_id=4),
models.Boy2Girl(b_id=random.randint(1,6),g_id=5),
models.Boy2Girl(b_id=random.randint(1,6),g_id=6),
models.Boy2Girl(b_id=random.randint(1,6),g_id=7),
models.Boy2Girl(b_id=random.randint(1,6),g_id=8),
]
models.Boy2Girl.objects.bulk_create(a)
Inquire
#通过关系表查询,查boy位男1对于的女的信息
#方法1:res = models.Boy2Girl.objects.filter(b__bname='男1').values('g__gname')
#方法2:
res = models.Boy2Girl.objects.filter(b__bname='男1').all()
for a in res:
print(res.g.gname)
#通过boy表查女的信息
#方法1: res = models.Boy.objects.filter(bname='男1').values('boy2girl__g__gname')
#方法2:
res = models.Boy.objects.filter(bname='男1').all()
for a in res:
for b in a.boy2girl_set.all():
print(b.g.gname)
3. to-many (not through a relational table)
models.py
class Boy1(models.Model):
bname = models.CharField(max_length=32, null=True)
g = models.ManyToManyField('Girl', null=True)
#他会生成一个boy1_g的表
class Girl1(models.Model):
gname = models.CharField(max_length=32, null=True)
Insert information
boys =[
models.Boy(bname='男1'),
models.Boy(bname='男2'),
models.Boy(bname='男3'),
models.Boy(bname='男4'),
models.Boy(bname='男5'),
models.Boy(bname='男6')
]
res = models.Boy1.objects.bulk_create(boys)
#
girls =[
models.Girl(gname='女1'),
models.Girl(gname='女2'),
models.Girl(gname='女3'),
models.Girl(gname='女4'),
models.Girl(gname='女5'),
models.Girl(gname='女6'),
models.Girl(gname='女7'),
models.Girl(gname='女8'),
]
models.Girl1.objects.bulk_create(girls)
Established relationship between the two
- Remove the objects of boy
- G then select the objects, and then the Add
添加
|删除
|查询
Girl's id
Add (add)
models.Boy1.objects.filter(bname='男1').first().g.add(1,2,3,4,5,2) #会自动去重保持唯一性也不会因为相同而报错
Delete (remove)
models.Boy1.objects.filter(bname='男1').first().g.remove(1)
Query (all)
models.Boy1.objects.filter(bname='男1').first().g.all()
Clear (clear)
models.Boy1.objects.filter(bname='男1').first().g.clear() #清除所有
important point
add add time if there will be automatically de-emphasis, he comes with a unique joint effect
4. many
https://www.cnblogs.com/pythonywy/p/11353202.html see here
And two .mysql djamgo-orm data type correspondence relationship
type of data | mysql | djamgo-snake |
---|---|---|
digital | tinyint | does not exist |
- | smallint | SmallIntegerField (Signed) PositiveSmallIntegerField (no sign) |
- | mediumint | does not exist |
- | int (unsigned) | IntegerField (Signed) PositiveIntegerField (no sign) |
- | bigint | BigIntegerField (Signed) PositiveBigIntegerField (no sign) |
- | decimal | DecimalField |
- | float | FloatField |
- | double | does not exist |
String | char | does not exist |
- | varchar | CharField |
- | text | TextField |
The date and time | date | DateField |
- | datetime | DateTimeField |
- | timestamp | does not exist |
And three .mysql djamgo-orm data corresponding to the type attribute
null 数据库中字段是否可以为空
db_column 数据库中字段的列名
default 数据库中字段的默认值
primary_key 数据库中字段是否为主键
db_index 数据库中字段是否可以建立索引
unique 数据库中字段是否可以建立唯一索引
class Meta:
### 联合唯一索引
unique_together=[
('b', 'g')
]
#### 联合索引
index_together = [
('b', 'g')
]
Four .djamgo data types that are only available in the admin
- EmailField (CharField):
字符串类型
correspondence information is not verified mail format - IPAddressField (Field,):
字符串类型
, Django Admin and ModelForm provides verification mechanism IPV4 - GenericIPAddressField (Field,):
字符串类型
, and the Django the Admin ModelForm Ipv4 and Ipv6 provide verification- parameter:
- protocol: specifies Ipv4 or Ipv6, 'both', "ipv4", "ipv6"
- unpack_ipv4: as if specified as True, then enter :: ffff: 192.0.2.1 when resolves to 192.0.2.1, open thorn function, protocol = "both"
- parameter:
- URLField (CharField):
字符串类型
, Django Admin and verification URL provided ModelForm - SlugField (as CharField):
字符串类型
, in the Django ModelForm the Admin and a verification support letters, numbers, underscore, hyphen (minus) - CommaSeparatedIntegerField (CharField):
字符串类型
, digital format must be comma-separated - UUIDField (Field,):
字符串类型
, and the Django ModelForm the Admin provides verification of the UUID format - That FilePathField will (Field,):
字符串
, and the Django ModelForm provide the Admin functions to read the file folder- parameter:
- path: file path
- match = None: Match Regular
- recursive = False: The following folders recursively
- allow_files = True: Allow file
- allow_folders = False: Allow file folder
- parameter:
- ImageField (FileField):
字符串类型
path stored in the database, upload files to a specified directory- parameter:
- Save the file upload path: upload_to = ""
- storage = None: storage component, the default django.core.files.storage.FileSystemStorage
- ImageField (FileField): database field names highly conserved upload pictures (string)
- height_field = None: save the width of the database field name to upload your pictures (string)
- parameter:
Five .djamgo properties that are only available in the admin
verbose_name: field names that appear in Admin
blank: Admin whether user allowed to enter the air
editable: Admin can edit whether
help_text: Admin in the message field
choices: Admin display content of the selection box, does not change the data in memory to avoid cross-table operation
- Such as: gf = models.IntegerField (choices = [(0, 'Sui He'), (1, 'large cousin'),], default = 1)
error_messages: custom error message (dictionaries), you want to customize the error message displayed;
- Import RegexValidator django.core.validators from
from django.core.validators Import The EmailValidator, URLValidator, DecimalValidator, MaxLengthValidator, MinLengthValidator, MaxValueValidator, MinValueValidator
such as:
Test = models.CharField (
MAX_LENGTH 32 =,
error_messages, = {
'C1': 'wrong priority information. 1 ',
' C2 ':' priority error information 2 ',
' C3 ':' priority error information. 3 ',
},
validators = [
RegexValidator (REGEX =' root_ \ D + ', message =' wrong ', code = 'C1'),
RegexValidator (REGEX = 'root_112233 \ D +', Message = 'and wrong', code = 'C2'),
the EmailValidator (Message = 'and wrong', code = 'C3'),]
)
- Import RegexValidator django.core.validators from