这是在django中为多个模型实例制作post方法的更简单方便的方法

时间:2018-03-29 13:30:59

标签: python django python-3.x django-models django-rest-framework

我有一个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)

Serializers.py

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']

1 个答案:

答案 0 :(得分:0)

我建议您使用通用视图中的CreateAPIViewhttp://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

中注册您的观点