Problem with unique_together and field override in ModelSerializer

433 views
Skip to first unread message

Michael Goffioul

unread,
Sep 11, 2020, 3:25:11 PM9/11/20
to Django REST framework
I have the following model:

class UnitData(models.Model):
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
    key = models.CharField(max_length=64)
    data = models.TextField(blank=True)

    class Meta:
        unique_together = ["unit", "key"]

I would like to rename the field 'unit' to 'device' in my serializer, so I've used the following:

class UnitDataBatchSerializer(serializers.HyperlinkedModelSerializer):
    device = serializers.HyperlinkedRelatedField(
            source='unit',
            view_name='unit-detail',
            queryset=Unit.objects.all())

    class Meta:
        model = UnitData
        fields = [ 'device', 'key', 'data' ]

However, I'm getting an exception when validating posted data. It appears the UniqueTogetherValidator will try to access the 'unit' field in the serializer, but it doesn't exist:

Is that expected? Or a bug? Is there a better way to rename the field in the serializer?

Thanks,
Michael.

Carl Nobile

unread,
Sep 11, 2020, 4:08:06 PM9/11/20
to django-res...@googlegroups.com
You may have to override the UniqueTogetherValidator to use the correct field.


~Carl


--
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-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/049037ba-0104-404e-a921-570992b91d45n%40googlegroups.com.


--
-------------------------------------------------------------------------------
Carl J. Nobile (Software Engineer)
carl....@gmail.com
-------------------------------------------------------------------------------
Reply all
Reply to author
Forward
0 new messages