2 years ago
#384914
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:
- Why isn't data read-only, like it would be if it were a "normal" serializer field?
- How can I say "save a new sourceif an identical one doesn't exist already?"
python
django
django-models
django-rest-framework
django-serializer
0 Answers
Your Answer