0

My task is for an administrator in my application to be able to create and update an employee's details. Given that django's user model simplifies authentication, I used it as a OnetoOneField in my Employee Model, representing the key as the employee ID (username).

My Model -

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=50, unique=True)
    date_of_join = models.DateField(blank=True, null=True)
    date_of_birth = models.DateField(blank=True, null=True)
    designation = models.CharField(max_length=255, null=True)
    mobile = models.CharField(max_length=255, null=True)
    personal_email = models.CharField(max_length=255, blank=True, null=True)
    official_email = models.CharField(max_length=255, blank=True, null=True)
    current_station = models.CharField(
        max_length=255, default="Chennai", null=True)

    def __str__(self):
        return self.name

Serializers -

class EmployeeSerializer(serializers.ModelSerializer):

    class Meta:
        model = Employee
        fields = ('user', 'name', 'date_of_join', 'date_of_birth',
                  'designation', 'mobile', 'landline', 'personal_email', 
                  'official_email', 'current_station')

My Model View Set:

class EmployeeListSet(viewsets.ModelViewSet):
    lookup_field = 'user'
    serializer_class = EmployeeSerializer
    queryset = Employee.objects.all()

Browsable API of a specific Employee filtered by user ID

As shown in the image, the user field shows me pk instead of user.username.

I am able to see the username in the HTML Form for POST in the browsable API, however the json does not return the username by default and rather returns pk.

I want to be able to lookup and update an employee's details based on the username (employee ID).

What I have tried -

I have tried redefining the user field as a SerializedMethodField that returns user.username, but lookup and POST method still requires the pk instead of username, so it doesn't solve the problem for me.

Nesting serialziers makes the nested serializer have to be read only, which again makes my task of updating employee details undesirable.

How can I lookup an employee object based on user.username instead of pk?

How can I associate an existing User object with an employee object during creation with the User object's username using modelviewsets? Is there a way to solve this without having to override or write my own create and update functions for the modelviewset?

  • This question was already asked [here](https://stackoverflow.com/questions/29068097/django-rest-framework-lookup-field-through-onetoonefield) – Sreevardhan Reddy Mar 01 '20 at 07:00
  • @SreevardhanReddy The question you have mentioned does not answer my query, as the solution proposed there is for GET and not CREATE/POST. – Vishhvak Srinivasan Mar 01 '20 at 07:52

0 Answers0