Skip to content Skip to sidebar Skip to footer

Getting "doesn't Exist Or Is M2m Field" Error On My Uuid (primary Key) When Trying To Save In Drf

I've written my own bulk save() because I can't get the internal save() method of ListSerializer to call the relevant method (create() & update()) depending on the query payloa

Solution 1:

The error comes from this line where Django compares update_fields you've provided with Model fields.

        if non_model_fields:
            raise ValueError("The following fields do not exist in this ""model or are m2m fields: %s"
                             % ', '.join(non_model_fields))

Unfortunately the error message is a little misleading because all fields with primary_key=True (like your uuid field) are filtered out, beside m2m ones.

        update_fields = frozenset(update_fields)
        field_names = set()

        for field in self._meta.fields:
            ifnot field.primary_key:
                field_names.add(field.name)
                ...
        non_model_fields = update_fields.difference(field_names)

That's the reason why non_model_fields are not empty and exception is raised.

To fix your problem, you need to get rid of uuid key from obj before saving.

        ...
        obj.pop('uuid')  # only if mutating validated_data doesn't bother you

        update_fields = [k for k,v in obj.items()]
        for k, v in obj.items():
            setattr(instance, k, v)
        instance.save(update_fields=update_fields)
        result.append(instance)

BTW you don't need this list comprehension to get update_fields - you can use obj.keys() which gives same result.

Solution 2:

Happens due to wrong field name(column name) use in django

Post a Comment for "Getting "doesn't Exist Or Is M2m Field" Error On My Uuid (primary Key) When Trying To Save In Drf"