Django Rest Framework - Cannot POST because username already exists

Viewed 182

I am working on a basic rest api with django rest framework. And my database is on MySQL. For one of the functions, when I try to POST, it gives me an error because there is a row with the same username already. I have set the model to have all three of its fields to be unique_together. Please help me understand where i am going wrong, heres snippets of what i have currently:

models.py:

class VolunteerHours(models.Model):
username = models.OneToOneField(Volunteer, models.DO_NOTHING, db_column='Username', primary_key=True) 
date = models.DateField(db_column='Date') 
hours = models.IntegerField(db_column='Hours')  

class Meta:
    managed = False
    db_table = 'volunteer_hours'
    unique_together = (('username', 'date', 'hours'),)

urls.py:

urlpatterns = [

path('timesheet/', views.TimesheetAPIView.as_view()),]

views.py:

from . import models
from . import serializers
from rest_framework import generics
from rest_framework import mixins

class TimesheetAPIView(generics.GenericAPIView, mixins.CreateModelMixin):
    serializer_class = serializers.VolunteerTimesheetSerializer

    def post(self, request):
        return self.create(request)

serializers.py:

class VolunteerTimesheetSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.VolunteerHours
        fields = '__all__'

The error im getting is:

 "username": [
        "volunteer hours with this username already exists."
    ]

What I want to happen is i can add as many rows with the same username as long as the date and hours are unique. Which are what is submit in my POST requests, but it says username already exists even if the date and hours are unique.

Please help.

Thank you!

1 Answers

You’ve created a OneToOne relationship with VolunteerHours and Volunteers, meaning only one of each can exist in a relationship. Like @DEEPAK KUMAR says, you’ll want to remove primary_key=True, but you’ll also want to change the relationship to be OneToMany via the ForeignKey field.

Related