Home > Software design >  ValueError: Cannot assign "1": "LeadFacilityAssign.assigned_facilities" must be
ValueError: Cannot assign "1": "LeadFacilityAssign.assigned_facilities" must be

Time:11-01

I've been trying to create an api endpoint to update my "lead" objects and add a list of facilities to them when sending a put request (each time a different amount of facilities). The lead objects already exist inside the database so do the facility objects. Since i need a date and time associated to each facility when they are being added to a lead i created the "LeadFacilityAssign" class. Since i wasn't able to get it to work i tried to do it just with a post request for now, during the lead creation process. I was told that i need to use bulk_create if i need to add more than one facility this way. I couldn't find anything on bulk_create inside the drf documentation so i decided to do this for now just with one facility and improve my code from there one issue at a time since i'm new to drf.

Does anyone know what is causing this error? I tried a few different things but nothing worked so far.

ValueError: Cannot assign "1": "LeadFacilityAssign.assigned_facilities" must be a "Facility" instance.

serializers.py

class LeadUpdateSerializer(serializers.ModelSerializer):
    is_owner = serializers.SerializerMethodField()
    assigned_facilities = serializers.IntegerField(required=True)
    datetime = serializers.DateTimeField(required=True)

    class Meta:
        model = Lead
        fields = (
            "id",
            "first_name",
            "last_name",
            "assigned_facilities",
            "datetime",
        )
        read_only_fields = ("id", "created_at", "agent", "is_owner")

    def get_is_owner(self, obj):
        user = self.context["request"].user
        return obj.agent == user
    
    def create(self, validated_data):
        assigned_facilities = validated_data.pop("assigned_facilities")
        datetime = validated_data.pop("datetime")
        instance = Lead.objects.create(**validated_data)
        instance.leadfacility.create(assigned_facilities=assigned_facilities,datetime=datetime)
        print(instance)
        return instance

models.py

class Facility(models.Model):
    name = models.CharField(max_length=150, null=True, blank=False)

    def __str__(self):
        return self.name

class Lead(models.Model):
    first_name = models.CharField(max_length=40, null=True, blank=True)
    last_name = models.CharField(max_length=40, null=True, blank=True)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

class LeadFacilityAssign(models.Model):
    assigned_facilities = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='leadfacility')
    lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='leadfacility')
    datetime = models.DateTimeField()

views.py

class LeadCreateView(CreateAPIView):
    permission_classes = [IsAuthenticated, IsLeadOwner]
    serializer_class = LeadUpdateSerializer

    def perform_create(self, serializer):
        serializer.save(agent=self.request.user)

class LeadUpdateView(UpdateAPIView):
    permission_classes = [IsAuthenticated, IsLeadOwner]
    serializer_class = LeadUpdateSerializer

    def get_queryset(self):
        return Lead.objects.all()

CodePudding user response:

You are trying to add Integer value into FK field.

You have 2 options. You can change the serializer field.

assigned_facilities = serializers.PrimaryKeyRelatedField(queryset=Facility.objects.all(), required=True, write_only=True)

OR

    assigned_facilities = serializers.IntegerField(required=True, write_only=True)
instance.leadfacility.create(assigned_facilities_id=assigned_facilities,datetime=datetime)

I would rather use 1 option.

  • Related