Cannot assign must be instance.

I created a serializer which stores the data from scanned barcode, the bar code contains the item_uuid, and the warehouse data, i having trouble assigning the returned item_uuid to the item foregin key to be able to use it to get the item data.

models.py

from django.db import models
from warehouse.models import itemLocation
import uuid
# Create your models here.

class scanned(models.Model):
    uuid = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, max_length=36)
    scanned_item = models.CharField(max_length=48)
    item_uuid = models.CharField(max_length=38)
    warehouse_number = models.IntegerField()
    item_location = models.CharField(max_length=6)
    scanned_at = models.DateTimeField(auto_now_add=True)
    item = models.ForeignKey(itemLocation, on_delete=models.CASCADE)
    # Warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE)

    def __str__(self):
        return self.item_uuid

    def save(self, *args, **kwargs):
        self.item_uuid = self.scanned_item.split()[0]
        self.warehouse_number = self.scanned_item.split()[1]
        self.item_location = self.scanned_item.split()[2]
        self.item = self.item_uuid                      # Error is on this line, how can i assign the returned item_uuid to the item 
        return super().save(*args, **kwargs)

serializer.py

from rest_framework import serializers
from .models import scanned

class scannedSerializer(serializers.ModelSerializer):
    class Meta:
        model = scanned
        fields = ['scanned_item']

views.py

from rest_framework.response import Response
from .serializer import scannedSerializer
from rest_framework import viewsets, status

# Create your views here.
class scannedViewSet(viewsets.ViewSet):   
    def create(self, request): #scanned/api/ (post)
        serializer = scannedSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)

Hi HamzaMa96,

Assuming ‘itemLocation’ model has a field called ‘uuid’, you can use the following line in your model save method:

self.item = itemLocation.objects.get(uuid=self.item_uuid)
1 Like