Hi, I have a basic one-to-many foreign key relationship (each product
has a company associated with it, one company can have multiple
products). I do not specify an explicit serializer relation for this
field (e.g. PrimaryKeyRelatedField) so it's using the FK definition
from the models ( company = models.ForeignKey(Company, models.CASCADE,
blank=True, null=True) )

I have overridden the .create() method in the Product serializer
(inherits from ModelSerializer) to use the company name that's passed
in, to look up the relevant ID (or create a new record) and assign it
to " validated_data['company'] = company_obj " and it works fine.

However, on the update (PATCH) where I also pass in the company name,
I get a validation error saying that it expects a primary key instead
of the name ("Incorrect type. Expected pk value, received str"). I
have added breakpoints in .update() and .partial_update() of the
Product serializer but the error seems to come from an earlier
validation routine. Could someone suggest where I can intercept the
validation process to translate the company name into an object and
put in validated_data['company'] , the same way I am doing in
.create() ?

I tried adding a field level validation, but that doesn't seem to make
a difference.

def validate_company(self, value):
        c, created = Company.objects.get_or_create(name = value)
        return c


TIA

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAMZO7wJT7-OyjxRdubPKOAzZk15iGOdSw_stLaDra%3DyHipqPLg%40mail.gmail.com.

Reply via email to