在django模型中不能在一个表中设置多个外键

w7t8yxp5  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(171)

我Map了同一个表中的两个外键(emp_name和code)。
每当我在LeaveRequest模块中创建一个请求时,emp_name和emp_code只显示id,如下图所示,但我希望显示名称。
有人能提出解决方案吗?
另外,我如何为不同的休假类型设置不同的条件,在哪里创建条件序列化程序或视图?
for循环是否是创建不同休假类型条件的好选项?

下面是我的代码:

模型.py

class Employee(models.Model):
    employee_code = models.IntegerField(unique=True,primary_key=True)
    employee_name = models.CharField(max_length=50,unique=True)

class LeaveRequest(models.Model):    
    emp_name = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='empl_name')
    emp_code = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='emp_code',default='')
    leave_type = models.CharField(choices=( ('CL', 'Casual leave'),
                                           ('SL', 'Sick leave'),
                                           ('ML', 'Medical leave'),
                                           ('Comp off', 'Compensation')   
    ),default='',max_length=20)

序列化程序.py

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

class LeaveRequestSerializer(serializers.ModelSerializer):
    
    class Meta:        
        model = LeaveRequest
        fields = '__all__'

查看次数.py

class Empcreate(CreateAPIView):  
    serializer_class = EmployeeSerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({
            "user": serializer.data,
            "message": "User Created Successfully..!",
        })

class LeaveRequest(CreateAPIView):    
    serializer_class = LeaveRequestSerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({
            "user": serializer.data,
            "message": "Request created successfully..!",
        })
xqk2d5yq

xqk2d5yq1#

您可以在管理页面中通过覆盖类的__str__方法来修复此问题:

# models.py

class Employee(models.Model):
    employee_code = models.IntegerField(unique=True,primary_key=True)
    employee_name = models.CharField(max_length=50,unique=True)

    def __str__(self):
        return self.employee_name

有几种方法可以根据休假类型获得不同的属性,最好的方法取决于您的用例。
您可以覆写序列化程式内的to_representation()方法:

# serializers.py
class LeaveRequestSerializer(serializers.ModelSerializer):
    
    def to_representation(self, instance):
        representation = super(LeaveRequestSerializer, self).to_representation(instance)
        if instance.type == 'CL':
            representation['...'] = ...
        return representation

    class Meta:        
        model = LeaveRequest
        fields = '__all__'

相关问题