Alfa Bravo
Alfa Bravo

Reputation: 1991

Slug and rename the same field in Django Serializer

If I have it correct (and this is the way I use it) SlugRelatedField in Django Serializer can be used to return the string value from the ID of a foreign-key field. Like I said I regularly do this. I also regularly change the field name in a table to something different by using CharField.

But how do I use both of these together? What I have so far is:

class ProductContainersSerializer(serializers.ModelSerializer):

    containernameid = serializers.SlugRelatedField(read_only=False, slug_field='containername', queryset=Productcontainernames.objects.all())
    container = serializers.CharField(source='containernameid')
    productid = serializers.SlugRelatedField(read_only=False, slug_field='productid', queryset=Productlist.objects.all())


    class Meta:
        model = Productcontainers
        fields = ('productid, 'container')

The model has two fields:

class Productcontainers(models.Model):
    containernameid = models.ForeignKey(Productcontainernames, on_delete=models.CASCADE) 
    productid = models.ForeignKey(Productlist, on_delete=models.CASCADE) 

The above would work fine, if it was not for the fact that when I run my code it says that I must include the containernameid due to the fact that I have declared it. This kind of defeats the purpose because now I basically send the same information through twice (as container and containernameid).

How can I return the string value (not id) of containernameid AND change the name of the field to container?

Current output: Error -> The field 'containernameid' was declared on serializer ProductContainersSerializer, but has not been included in the 'fields' option.

Expected (desired) output:

0:{productid: "Prod1", container: "Box"}
1:{productid: "Prod2", container: "Crate"}
2:{productid: "Prod3", container: "Crate"}
3:{productid: "Prod4", container: "Box"}  etc

Output without changing Serializer in any way:

0:{productid: 1, containernameid : 1}
1:{productid: 2, containernameid : 2}
2:{productid: 3, containernameid : 2}
3:{productid: 4, containernameid : 1}  etc

Upvotes: 1

Views: 880

Answers (1)

JPG
JPG

Reputation: 88499

If I'm understood your question correctly, the StringRelatedField() would apt in your context

class ProductContainersSerializer(serializers.ModelSerializer):
    productid = serializers.StringRelatedField()
    container = serializers.StringRelatedField(source='containernameid')

    class Meta:
        model = Productcontainers
        fields = ('productid', 'container')



NOTE:
StringRelatedField may be used to represent the target of the relationship using its __unicode__ or __str__ method.

Upvotes: 3

Related Questions