我想创建一个Django模型,它是2个模型的组合,如
class Employee(models.Model):
emp_id = models.CharField(max_length=45, primary_key=True, null=False)
name = models.CharField(max_length=45)
age = models.IntegerField()
dob = models.DateField()
addr = models.CharField(max_length=45)
class designtion(models.Model):
emp_id = models.charField(max_length=45)
role_name = models.charField(max_length=45)
starts_from = models.DateField()
ends_on = models.DateField()
我想从这些2中创建一个组合模型,
class EmpDetails(models.Model):
name = models.CharField(max_length=45)
role_name = models.charField(max_length=45)
我正在使用 django-rest-framework 这是他们最喜欢的方式吗?
答案 0 :(得分:1)
如果您愿意,可以尝试一下。
<强> models.py 强>
class designtion(models.Model):
emp_id = models.charField(max_length=45)
role_name = models.charField(max_length=45)
starts_from = models.DateField()
ends_on = models.DateField()
employee = models.ForeignKey(Employee, related_name="designition_employee")
<强> serializers.py 强>
from .models import designtion, EmpDetails
class DesigntionSerializer(serializers.ModelSerializer):
hr_employee = serializers.ReadOnlyField(source='employee.name', read_only=True)
class Meta:
model = designtion
exclude = ()
def create(self, validated_data):
name = validated_data.get('employee').name
role_name = validated_data.get('role_name')
EmpDetails.objects.create(name=name, role_name=role_name)
return super(DesigntionSerializer, self).create(validated_data)
在将员工字段添加到设计模型时,不要忘记迁移。
答案 1 :(得分:1)
如果要为Employee
和designtion
创建多对多关系(顺便说一句,你应该将其大写),Django支持M2M Field
它基本上创建了一个JOIN表,但它为您提供了执行查找,创建等所需的所有方法。
如果您希望将来证明以防万一您离开Django并希望所有模型和方法都可以重复使用,那么您可以手动创建EmpDetails
表:
class EmpDetails(models.Model):
... //other fields omitted, add as you need them
employee = models.ForeignKey(Employee)
designtion = models.ForeignKey(designtion)