gpt4 book ai didi

django-rest-framework - 如何从django rest框架中的多个模型获取数据

转载 作者:行者123 更新时间:2023-12-05 03:52:50 24 4
gpt4 key购买 nike

我是 Django Rest API 的新手,所以请帮忙。

我有两个模型:

class Department(models.Model):
name = models.CharField(max_length = 50)
location = models.CharField(max_length=20)
dept_code = models.CharField(max_length=5)

class Employee(models.Model):
name = models.CharField(max_length = 50)
email = models.EmailField()
mobile = models.CharField(max_length=10)
department = models.ForeignKey(Department, on_delete= models.CASCADE)'

而各自的序列化器是:

class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = '__all__'

class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Department
fields = '__all__'

我想像这样检索数据

{
emptId : 1,
empName : 'John',
empEmail : 'John@gmail.com',
empMobile : '1111111111',
deptId : 1,
deptName : 'Accounts',
deptLocation : 'Pune',
deptCode : 'ACC'
}

如何获取以上数据。请帮助我

最佳答案

在你的Serializers.py

class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Department
fields = '__all__'

class EmployeeSerializer(serializers.ModelSerializer):
department = DepartmentSerializer(many=False)

class Meta:
model = Employee
fields = ('empId','empName','empEmail','empMobile','department')

使用它您将获得首选的嵌套对象结构。

如果你想得到扁平结构那么

class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Department
fields = '__all__'

class EmployeeSerializer(serializers.ModelSerializer):
department = DepartmentSerializer(many=False)
depId = serializers.IntergerField(source='department.id')
depName = serializers.CharField(source='department.name')
depLocation = serializers.CharField(source='department.location')
depCode = serializers.CharField(source='department.dept_code')
class Meta:
model = Employee
fields = ('empId','empName','empEmail','empMobile','depId','depName','depLocation','depCode','department')

希望你能明白如果您不想在 get 方法中使用 department 对象,请在 department 字段的参数中添加 write_only=True

查看更多 readonly and writeonly

medium

关于django-rest-framework - 如何从django rest框架中的多个模型获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62024414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com