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
一、同时新增数据到两个数据库表
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):
project_list_dict = {}
project_detail_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]
try:
ProjectList.objects.get(project_name=request.data.get('project_ame'))
return xxx
except Account.DoesNotExist:
try:
project_create = ProjectList.objects.update_or_create(defaults=project_list_dict, project_name=project_list_dict["project_ame"])
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
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',)
出处:https://www.cnblogs.com/lsc-blog/p/16813732.html