1 year ago

#384914

test-img

nebulaeandstars

DRF - How do you include foreign data within a Serializer?

I have a Model that looks a bit like this:

class Foo(models.Model):
    data = models.ForeignKey(Data, on_delete=models.CASCADE)
    source = models.ForeignKey(Source, on_delete=models.CASCADE)
    # other fields...

In this case I'd like to show the full models for data and source, rather than just their IDs. I also need data to be read-only as it's generated automatically. My Serializer looks like this:

class FooSerializer(serializers.ModelSerializer):
    data = DataSerializer(read_only=True)
    source = SourceSerializer()

    class Meta:
        model = Foo
        fields = ["data", "source"]
        read_only_fields = ["data"]

What I don't quite understand is:

  1. Why isn't data read-only, like it would be if it were a "normal" serializer field?
  2. How can I say "save a new source if an identical one doesn't exist already?"

python

django

django-models

django-rest-framework

django-serializer

0 Answers

Your Answer

Accepted video resources