简体   繁体   中英

DRF: data structure in serializer or view?

Given the models below, I've been trying to figure out how to return the data structure I have in mind (also below) using Django REST Framework.

How would this be accomplished within a serializer, or does such a data structure need to be built within a view using traditional Django-style queries?

About

Basically, a word is created, users submit definitions for that word, and vote on each definition (funniest, saddest, wtf, etc.)

models.py

from django.db import models


class Word(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    word = models.CharField()
    timestamp = models.DateTimeField()


class Definition(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    word = models.ForeignKey(Word, on_delete=models.CASCADE)
    definition = models.CharField()
    timestamp = models.DateTimeField()


class Vote_category(models.Model):
    category = models.CharField()


class Vote_history(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    definition = models.ForeignKey(Definition, on_delete=models.CASCADE)
    timestamp = models.DateTimeField()
    vote = models.ForeignKey(Vote_category, on_delete=models.CASCADE)

Expected Query Result Structure

word: 'hello',
definitions: [
    {
        user: 'alice',
        definition: 'an expression of greeting',
        votes: {
            funny: 3,
            sad: 1,
            wtf: 7
        },
        votes_total: 11
    },
    etc...
]

Thanks!

The schema you attached can (and should) be generated using Django REST Framework Serializers; the nested elements of your schema can be generated using nested serializers. Generally these serializers will inherit from the ModelSerializer .

Here is an example of the nested serializers you would use to begin to construct your schema:

class WordSerializer(serializers.ModelSerializer):
    """Serializer for a Word"""
    definitions = DefinitionSerializer(many=True)

    class Meta:
        model = Word
        fields = ('word', 'definitions')

class DefinitionSerializer(serializers.ModelSerializer):
    """Serializer for a Definition"""
    user = UserSerializer(read_only=True)
    votes = VoteSerializer(many=True)

    class Meta:
        model = Word
        fields = ('definition', 'user', 'votes')

One part of the schema you have listed which may be more complicated is the map of vote category to vote count. DRF naturally would create a structure which is a list of objects rather than a single object as your schema has. To override that behavior you could look into creating a custom ListSerializer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM