Home > Net >  How to solve "field must be unique" in django?
How to solve "field must be unique" in django?

Time:07-19

I am creating an app with vue and django but struggle with getting information from serializer. my models look like this:

models.py

from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

class Order(models.Model):
    name = models.CharField(max_length=255) 
    posted_by = models.ForeignKey(Profile, on_delete=models.CASCADE)

class Offer(models.Model):
    order_related = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='offers')
    author = models.ForeignKey(Profile, on_delete=models.CASCADE)

serializers.py:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ("user",)


class OfferSerializer(serializers.ModelSerializer):
    author = ProfileSerializer()
    class Meta:
        model = Offer
        fields = ("id", "order_related", 
                  "author", 
         )


class OrderSerializer(serializers.ModelSerializer):
    posted_by = ProfileSerializer()

    class Meta:
        model = Order
        fields = ("id",  "posted_by", "name")

views.py:

class OfferView(ListModelMixin, GenericAPIView, CreateModelMixin):

    queryset = Offer.objects.all()
    serializer_class = OfferSerializer 

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

when i send info to this view:

     const formData = {
      order_related: this.$route.params.order_id,
      author: {user: localStorage.getItem("user")},
    } 
    
        axios  
    .post("api/v1/offers/", formData)

i get error:

{"user":["Values of field must be unique."]}

Is there any way to override this?

P.S. To write AbstactUser model etc. - not a way

To send another request in order to get by id for detailed info is also not the best

CodePudding user response:

Profile class having only 1 OneToOneField looks redundant.

You can simply work on User class.

CodePudding user response:

How about:

  • views.py
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response

class OfferView(ListModelMixin, GenericAPIView):
    queryset = Offer.objects.all()
    serializer_class = OfferSerializer 

    def post(self, request, *args, **kwargs):
        data = request.data
        order_id = data.get('order_related')
        user_id = data.get('author', {}).get('user')
        try:
            order_id = int(order_id)
            user_id = int(user_id)
        except (TypeError, ValueError):
            raise ValidationError(f'Invalid post data: {order_id=};{user_id=}')
        profile = Profile.objects.get(user_id=user_id)
        order = Order.objects.get(id=order_id)
        obj = self.queryset.create(order_related=order, author=profile)
        return Response(self.serializer_class(obj).data)
  • Related