user2061057
user2061057

Reputation: 1022

Django REST framework: deserializing an existing foreign key fails

I have Foo objects that are "owned" by an Organization. I get the current Organization from the logged-in User in my request handler:

models.py:

class Organization(models.Model):
    name = models.CharField(max_length=255)

class Foo(models.Model):
    ... some other fields ...
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)

serializers.py:

class FooSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    organization = OrganizationSerializer(read_only=True)

    """ Create and return a new instance, given the validated data """
    def create(self, validatedData):
        return OverlayDesign.objects.create(**validatedData)

    """ Update and return an existing instance, given the validated_data """
    def update(self, instance, validatedData):
        instance.organization = validatedData.get('organization', instance.organization)
        instance.save()
        return instance

views.py:

def createFoo(request):
    data = JSONParser().parse(request)

    # Get the organization of the logged-in user
    data["organization"] = OrganizationSerializer(request.user.account.organization).data

    serializer = FooSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return JSONResponse(serializer.data, status=201)
    return JSONErrorResponse(serializer.errors, status=400)

When I create a new Foo, I want it to be owned by the current Organization. The problem is that I don't understand why the Organization is not deserialized? No matter what I do I just get:

django.db.utils.IntegrityError: null value in column "organization_id" violates not-null constraint

How should I deliver the current Organization to the FooSerializer ?

Upvotes: 0

Views: 296

Answers (1)

Pierre Alex
Pierre Alex

Reputation: 473

OrganizationSerializer is set with the readonly option => you won't get anything to match the current organization.

You should take a look at : http://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield

Upvotes: 1

Related Questions