我有一个Employee
类,其中有几个ForeignKey
个实例。我正在使用django rest frame工作,我还创建了一个序列化器,下一步是创建一个POST
方法来创建Employee
。我可以方便地使用哪种方法来实现这一目标?
class Employee(models.Model):
"""
Model, which holds general information of an employee.
"""
user = models.OneToOneField(User,related_name='users',
on_delete=models.CASCADE)
photo_logo = models.FileField()
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
company = models.ForeignKey(
'hr.Company',
verbose_name='Company',
related_name='companies',
null=True, blank=True,
)
marital_status = models.ForeignKey(MaritalStatus)
identification_type = models.ForeignKey(IdentificationType)
class EmployeeSerializer(serializers.ModelSerializer):
designation = GroupListSerializer()
# department = GroupListSerializer()
# user = UserSerializer()
# address = AddressSerializer()
# em_contact = EmergencyContactSerializer()
# address = EmergencyContactSerializer()
class Meta:
model = Employee
fields = ['id','user','photo_logo','phone_number','dob', 'gender', 'hr_number', 'company', 'marital_status', 'identification_type',
'tax_id_number','joining_date', 'designation', 'department']
答案 0 :(得分:0)
我建议您使用通用视图中的CreateAPIView
:http://www.django-rest-framework.org/api-guide/generic-views/#createapiview
因此,您必须向views.py
添加课程。它可能看起来像这样:
from rest_framework import generics
from .serializers import EmployeeSerializer
class CreateEmployeeView(generics.CreateAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer
另外,请勿忘记在urls.py