1

Models:

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

    def __unicode__(self):
        return self.name

class SomeThing(models.Model):
    own_id = models.IntegerField(unique=True)
    description = models.CharField(max_length=255, blank=True)
    owner = models.ForeignKey(Owner, blank=True, null=True)

def __unicode__(self):
    return self.description

Serializers:

class OwnerNameField(serializers.RelatedField):
    def to_internal_value(self, data):
        pass

    def to_representation(self, value):
        return value.name

    def get_queryset(self):
        queryset = self.queryset
        if isinstance(queryset, (QuerySet, Manager)):
            queryset = queryset.all()
        lista = [Owner(name="------------")]
        lista.extend(queryset)
        return lista

class OwnerSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Owner
        fields = ('name', 'id')

class ThingSerializer(serializers.ModelSerializer):
    owner = OwnerNameField(queryset=Owner.objects.all())

    class Meta:
        model = SomeThing
        fields = ('own_id', 'description', 'owner')

Basically it works as intended. But when i add some fields to Owner class i would like to see all these fields in output of ThingSerializer (and be able to parse them - string doesn't suit here). I could change field owner to owner = OwnerSerializer() which gives me what i need. But when i want to add SomeThing object (tested in API browser) i also need add new Owner object - and i don't want it, i want use existing Owner object. How can i achieve it?

MoonWolf
  • 91
  • 1
  • 2
  • 7
  • 2
    You need to override `.create` or/and `.update` methods in `ThingSerializer`, [look at DRF docs](http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations) – devxplorer Oct 16 '16 at 08:18
  • DRF doesn't handle that for you automatically. As Wonder says, override the create / update methods on your serializer. – wobbily_col Oct 16 '16 at 15:32
  • Yes, this partially works as i wanted it to (i may do whatever i want in those methods). But it wouldn't replace fields in DRF browser's built-in POST form - there i still have Owner's *name* field instead of drop-down list of owners. – MoonWolf Oct 16 '16 at 15:40
  • Apart that i had to introduce horrible hacks as DRF validates data and i can't put arbitrary data into my POST payload. It works, but it is ugly and full of antipattern stuff :/ I'm sure there's better solution - i'm just too newbie at this to figure it out... – MoonWolf Oct 16 '16 at 22:18

1 Answers1

0

Finally i got it. This question describes exactly my problem and provided answers work as a charm!

Community
  • 1
  • 1
MoonWolf
  • 91
  • 1
  • 2
  • 7