Django REST Framework序列化与

时间:2019-07-08 06:41:47

标签: django django-rest-framework

假设我们有下一个模型:

class Radio(models.Model):
    name = models.CharField(...)

class Artist(models.Model):
    name = models.CharField(...)

class Song(models.Model):
    title = models.CharField(...)
    artist = models.ForeignKey(Artist, ...)

class Reproduction(models.Model):
    song = models.ForeignKey(Song...)
    radio = models.ForeignKey(Radio...)
    date = models.DateTimeField(...)

我应该如何创建序列化程序并查看是否可以通过POST接收: title: "Song title", artist:"Artist name", radio:"Radio name", date:"Reproduction date",如果艺术家和歌曲不存在,则需要创建它们。

谢谢。

3 个答案:

答案 0 :(得分:0)

如果您想在模型中添加这种逻辑,则可以对视图的perform_createcreate方法进行覆盖,并在反序列化之前创建艺术家/歌曲。

答案 1 :(得分:0)

您可以创建如下的序列化器

from rest_framework import serializers
class SARSerializer(serializers.ModelSerializer):
    song = serializers.CharField()
    artist = serializers.CharField()
    radio = serializers.CharField()

    def create(self, validated_data):
        radio, _ = Radio.objects.get_or_create(
            name=validated_data.get('radio'))
        artist, _ = Artist.objects.get_or_create(
            name=validated_data.get('artist'))
        song, _ = Song.objects.get_or_create(
            title=validated_data.get('title'), artist=artist)
        self.instance = Reproduction.objects.create(song=song, radio=radio, date=validated_data.get("date"))

    @property
    def data(self):
        return {
           "radio": self.instance.radio.name,
           "artist": self.instance.song.artist.name,
           "song": self.instance.song.title,
           "date": self.instance.name,
        }

    class Meta:
        model = Reproduction
        fields = ['song', 'artist', 'radio', 'date']

答案 2 :(得分:0)

请尝试此操作。.您必须使序列化程序仅用于传入数据验证,然后将所有数据一个一保存在视图中。.

serializes.py

SELECT CustomerID, OrderYear, AVG(CustomerPoints) AS (CustomerPoints) 
FROM TABLE
GROUP BY CustomerID, OrderYear

views.py

from rest_framework.serializers import(
     CharField,
     Serializer,
     )

lass SaveDataSerializer(Serializer):
    title = CharField()
    artist = CharField()
    radio = CharField()
    date = DateField()