Additional field while serializing django rest framework

前端 未结 3 813
太阳男子
太阳男子 2021-01-30 12:46

I am a newbie to django rest framework and have created a sample Employee model.

My models.py:

class Employees(models.Model         


        
3条回答
  •  礼貌的吻别
    2021-01-30 13:19

    Provided that the Employee is a login user, then most of us will use django.auth.User, I will share how Employee can be implemented as another Profile (extension of django User). Also with the addition of full_name.read_only, first_name.write_only, and last_name.write_only

    # models.py
    class Employee(models.Model):
        """User Profile Model"""
        user = models.OneToOneField('auth.User')
    
    # serializers.py
    class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
        username = serializers.CharField(source='user.username')
        email = serializers.EmailField(source='user.email')
    
        first_name = serializers.CharField(
                source='user.first_name', write_only=True)
        last_name = serializers.CharField(
                source='user.last_name', write_only=True)
        name = serializers.CharField(
                source='user.get_full_name', read_only=True)
    
    
        class Meta:
            model = Employee
            fields = (
                'url', 'username', 'email',
                'first_name', 'last_name', 'name')
            depth = 1
    

提交回复
热议问题