A
A
airwave2018-09-11 13:39:31
Django
airwave, 2018-09-11 13:39:31

Django Rest Framework, how to properly implement serializers?

Good afternoon!
Let's say there are two models

class UserProfile(AbstractUser):
    middle_name = models.CharField(max_length=1000, blank=True, null=True)
    type = models.ForeignKey(UserType, blank=True, null=True, on_delete=models.SET_NULL)

class Driver(models.Model):
    first_name = models.CharField(max_length=1000, blank=True, null=True)
    middle_name = models.CharField(max_length=1000, blank=True, null=True)
    last_name = models.CharField(max_length=1000, blank=True, null=True)
    driver_license = models.CharField(max_length=1000, blank=True, null=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL)

Those. There are drivers who are tied to a specific user. And serializers to read them:
class UserProfileReadSerializer(serializers.ModelSerializer):
    type = UserTypeSerializer()
    class Meta:
        model = UserProfile
        fields = ['id', 'username', 'last_name', 'first_name', 'middle_name', 'email', 'type', 'password', 'is_superuser', 'last_login', 'date_joined']

class DriverReadSerializer(serializers.ModelSerializer):
    user = UserProfileReadSerializer()
    class Meta:
        model = Driver
        fields = ['id', 'last_name', 'first_name', 'middle_name', 'driver_license', 'user']

The fact is that when requesting a list of drivers, the user field gives out a complete set of user data (which is, in principle, logical and understandable), and the user also has a nested user type, and this is additional. data, and as a result, a big footcloth, but I would like to issue only username to visually display the driver's belonging to the user, and it is username, not id.
Question: what is the best way to implement this? Do I need to make a separate serializer for the user with only the username field? Or are there better solutions?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question