- models:比如有以下三个模型
from django.db import models
"""
基类,其他类继承即可获得对应的字段
"""
class BaseModel(models.Model):
updated_tm = models.DateTimeField(auto_now=True)
created_tm = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
"""
项目列表
"""
class ProjectList( BaseModel):
project_id = models.AutoField(help_text="项目ID", primary_key=True)
project_name = models.SlugField(max_length=128, help_text="项目名称", unique=True)
class Meta:
db_table = 'project_list'
verbose_name = '项目列表信息'
verbose_name_plural = verbose_name
"""
项目详情
"""
class ProjectDetail(BaseModel):
project_introduction = models.CharField(max_length=128, help_text="用户简介")
project_info = models.ForeignKey(to=ProjectList, on_delete=models.DO_NOTHING, db_constraint=False, related_name='user')
class Meta:
db_table = project_detail'
verbose_name = '项目详情信息'
verbose_name_plural = verbose_name
一、同时新增数据到两个数据库表
- views
from rest_framework import filters, mixins, generics
from rest_framework.viewsets import GenericViewSet
class ProjectListView(mixins.CreateModelMixin, GenericViewSet):
queryset = Account.objects.filter(is_delete=0).all().order_by("-created_tm")
def create(self, request, *args, **kwargs):
# 先定义两个dict
project_list_dict = {}
project_detail_dict = {}
# 使用 ._meta.get_fields() 获取数据库表的全部字段,再使用field.name获取全部的字段名称,放入各自的dict,不存在的自动忽略掉
for item in request.data.items():
if item in [field.name for field in ProjectList._meta.get_fields()]:
project_list_dict [item[0]] = item[1]
elif item in [field.name for field in ProjectDetail._meta.get_fields()]:
project_detail_dict [item[0]] = item[1]
# 从上面的models可以看到,项目详情与项目列表两张表是有关联的,所以,新增数据的时候,先现在列表,新增成功,生成ID后,再新增详情,并通过ID与列表数据关联起来
# 检查项目是否存在,项目名称唯一约束,Serializer内设置必填
try:
# 存在就直接失败
ProjectList.objects.get(project_name=request.data.get('project_ame'))
return xxx
except Account.DoesNotExist:
# 如果不存在,先调用ProjectList表新增数据
try:
project_create = ProjectList.objects.update_or_create(defaults=project_list_dict, project_name=project_list_dict["project_ame"])
# 如果ProjectList表新增数据成功,则通过project_info,在ProjectDetail新增对应的数据
if project_create:
project_id = ProjectList.objects.filter(project_name=project_list_dict["project_ame"]).values('project_id').first()
ProjectDetail.objects.update_or_create(defaults=project_detail_dict, project_info=project_id["project_id"])
return xxx
except Exception as e:
return e
二、同时返回两个表的数据(插拔式)
- 插拔式的好处:即插即用,需要时才调用,不需要则不调用
- 从ProjectDetail这个models我们可以看到,是没有定义project_id和project_name的,但我们是与ProjectList关联的,所以,我们可以通过project_info,返回ProjectList已定义的project_id和project_name
# 我们只需要把ProjectDetail改成以下这样子就可以了
class ProjectDetail(BaseModel):
project_introduction = models.CharField(max_length=128, help_text="用户简介")
project_info = models.ForeignKey(to=ProjectList, on_delete=models.DO_NOTHING, db_constraint=False, related_name='user')
class Meta:
db_table = project_detail'
verbose_name = '项目详情信息'
verbose_name_plural = verbose_name
@property
def project_id(self):
return self.project_info.project_id
@property
def project_name(self):
return self.project_info.project_name
# 然后在序列化器内直接调用project_id和project_name即可
class ProjectDetailSerializer(serializers.ModelSerializer):
class Meta:
model = ProjectDetail
fields = ('project_id', 'project_name', 'project_introduction',)
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Django之同时新增数据到两个数据库表与同时返回两个表的数据(插拔式) - Python技术站