我基本上是Rest框架的新进入者,对Django来说相对较新。我正在使用Employee Rest API,我使用Django模型创建了Employee - Department表。我在Employee的部门ID和部门部门ID之间分配了外键关系。现在我想使用PUT操作更新Employee表。但是当我更新Employee.dept_id时,它没有使用新值更新。据我所知,由于它是一个只读字段,我无法更新它。如何将其更改为写字段?这样我就可以更新员工表中的部门ID。
models.py
class Department(models.Model):
dept_id = models.IntegerField(primary_key=True)
dept_name = models.CharField(max_length=30)
def __str__(self):
return self.dept_id
class Meta:
ordering = ('dept_id',)
class Employee(models.Model):
first_name = models.CharField(max_length=30,blank=True)
last_name = models.CharField(max_length=30,null=True,blank=True)
emp_id = models.AutoField(primary_key=True)
hire_date = models.DateField(default=datetime.date.today)
email_id = models.EmailField(blank=True)
dept = models.ForeignKey(Department, null=True,blank=True,related_name="dept")
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
class Meta:
ordering = ('emp_id',)
以上型号的序列化器
serializers.py
class DepartmentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Department
fields = ('dept_id','dept_name')
class EmployeeSerializer(serializers.ModelSerializer):
dept_id = DepartmentSerializer().get_fields()
class Meta:
model = Employee
fields = ('emp_id','last_name','first_name','hire_date','email_id', 'dept_id')
views.py
@api_view(['GET','POST'])
def employee_list(request, format=None):
"""
List all employees, or create a new employee
"""
if request.method == 'GET':
employees = Employee.objects.all()
serializer = EmployeeSerializer(employees,many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = EmployeeSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET','PUT','DELETE'])
def employee_detail(request, pk, format=None):
"""
Retrieve, update or delete a employee.
"""
try:
employee = Employee.objects.get(pk=pk)
except Employee.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method=='GET':
serializer = EmployeeSerializer(employee)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = EmployeeSerializer(employee,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method=='DELETE':
employee.delete()
return Response(status=status.HTTP_204_NO_CONTENT)