7.连表操作
利用双下划线和 _set 将表之间的操作连接起来
一、数据表结构
from django.db import models
class UserProfile(models.Model):
user_info = models.OneToOneField('UserInfo',on_delete=None)
username = models.CharField(max_length=64)
password = models.CharField(max_length=64)
def __str__(self):
return self.username
class UserInfo(models.Model):
user_type_choice = (
(0, u'普通用户'),
(1, u'高级用户'),
)
user_type = models.IntegerField(choices=user_type_choice)
name = models.CharField(max_length=32)
email = models.CharField(max_length=32)
address = models.CharField(max_length=128)
def __str__(self):
return self.name
class UserGroup(models.Model):
caption = models.CharField(max_length=64)
user_info = models.ManyToManyField('UserInfo')
def __str__(self):
return self.caption
class Host(models.Model):
hostname = models.CharField(max_length=64)
ip = models.GenericIPAddressField()
user_group = models.ForeignKey('UserGroup')
def __str__(self):
return self.hostname
二、一对一查询
user_info_obj = models.UserInfo.objects.filter(id=1).first()
print(user_info_obj.user_type)
print(user_info_obj.get_user_type_display())
print(user_info_obj.userprofile.password) #这里userprofile是小写。因为在数据库中全部是小写
user_info_obj = models.UserInfo.objects.filter(id=1).values('email', 'userprofile__username').first()
print(user_info_obj.keys())
print(user_info_obj.values())
三、一对多查询
类似一对一
1、搜索条件使用 __ 连接
2、获取值时使用 . 连接
四、多对多操作