带3个外键的嵌套序列化器。如何实现GET和POST?

时间:2018-09-25 11:01:09

标签: django api serialization django-rest-framework

class Author(models.Model):

   first_name = models.CharField(max_length=255)

   last_name = models.CharField(max_length=255)

   age = models.IntegerField()

//

class Editor(models.Model):

   first_name = models.CharField(max_length=255)

   date_edition = models.DateTimeField(default=datetime.now)

   status = models.BooleaField(default=True)

//

class Book_Manufacturer(models.Model):

   name = models.CharField(max_length=255)

   year_production = models.DateTimeField(default=datetime.now)

//

class Book(models.Model):

   author = models.models.ForeignKey(Author, on_delete=models.CASCADE)

   editor = models.models.ForeignKey(Editor, on_delete=models.CASCADE)

   book_manufacturer = models.models.ForeignKey(Book_Manufacturer, on_delete=models.CASCADE)

   title = models.CharField(max_length=255)

   year = models.DateTime(default=datetime.now)

有人可以帮助我吗?当我有GET方法时,如何将带有3 Foreign_key的Book序列化并显示所有详细信息? (所有详细信息=图书详细信息+图书制造商+编辑+作者)

如果我想创建包含所有信息的Book,那么POST方法又将如何实现?

PS:在实际应用中,我有一个带有3个外键的模型,就像示例一样。我在这里使用了一个幼稚的方法示例,它不是我的真实模型字段和类名XD,只是一个示例。

2 个答案:

答案 0 :(得分:1)

您可以这样定义序列化器:

但是要创建一本新书,您可以在BookSerializer中定义create方法并在那里创建所有新obj

class AuthorSerializer(ModelSerializer):
    class Meta:
        model = Author
        fields = ('first_name', 'last_name', 'age')

class EditorSerializer(ModelSerializer):
    class Meta:
        model = Editor
        fields = ('first_name', 'date_edition', 'status')

class Book_ManufacturerSerializer(ModelSerializer):
    class Meta:
        model = Book_Manufacturer
        fields = ('name', 'year_production')


class BookSerializer(ModelSerializer):

    author = AuthorSerializer()
    editor = EditorSerializer()
    book_manufacturer = Book_ManufacturerSerializer()

    class Meta:
        model = Book
        fields = ('author', 'editor', 'book_manufacturer', 'title', 'year')
   def create(self, validated_data):
       author = validated_data.pop('author')
       editor = validated_data.pop('editor')
       book_manufacturer = validated_data.pop('book_manufacturer')

       author_obj = Author.objects.create(first_name=author['first_name'], last_name=author['last_name'])

       # do it for editor and book_manufacturer
       book = Book.objects.create(author=author_obj, editor=editor_obj, book_manufacturer=book_manufacturer_obj, title=validated_data['title'], year=validated_data['year'])

       return validated_data

答案 1 :(得分:1)

class BookSimpleSerializer(ModelSerializer):
    class Meta:
        model = Book
        fields = ('author', 'editor', 'book_manufacturer', 'title', 'year')

    def create(self, validated_data):
        return Book(**validated_data)