Django DRF - 将外键字段包含在序列化程序中

时间:2017-01-09 19:32:34

标签: django serialization relationship django-rest-framework

如何添加' platform_description'字段是battlesSerializer结果的一部分吗?

模型

类战(models.Model):

# Fields
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
wager = models.FloatField(max_length=30)
battle_rules = models.CharField(max_length=30,null = True,blank = True)
accepting_time = models.DateTimeField()
offer_expiration_time = models.DateTimeField(null = True,blank = True)
battle_time = models.DateTimeField(null = True,blank = True)
rake = models.FloatField()

# Relationship Fields
platform_id = models.ForeignKey('platforms.game_platforms', related_name='seal')

class Meta:
    ordering = ('-created',)

def __unicode__(self):
    return u'%s' % self.id

def get_absolute_url(self):
    return reverse('platforms_battles_detail', args=(self.id,))


def get_update_url(self):
    return reverse('platforms_battles_update', args=(self.id,))

class game_platforms(models.Model):

# Fields
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
platform_description = models.CharField(max_length=30)


class Meta:
    ordering = ('-created',)

def __unicode__(self):
    return u'%s' % self.id

def __str__(self):
    return '%s' % self.platform_description

def get_absolute_url(self):
    return reverse('platforms_game_platforms_detail', args=(self.id,))


def get_update_url(self):
    return reverse('platforms_game_platforms_update', args=(self.id,))

串行

class battlesSerializer(serializers.ModelSerializer):

class Meta:
    model = models.battles
    fields = (
        'id', 
        'created', 
        'last_updated', 
        'wager', 
        'battle_rules', 
        'accepting_time', 
        'offer_expiration_time', 
        'battle_time', 
        'rake',
    )

class game_platformsSerializer(serializers.ModelSerializer):

class Meta:
    model = models.game_platforms
    fields = (
        'id', 
        'created', 
        'last_updated', 
        'platform_description', 
    )

1 个答案:

答案 0 :(得分:2)

您可以使用SerializerMethodField

class battlesSerializer(serializers.ModelSerializer):

    platform_description = serializers.SerializerMethodField()

    def get_platform_description(self, obj):

        # Use a try - except block if needed

        return obj.platform_id.platform_description

    class Meta:
        model = models.battles
        fields = (
            'id', 
            'created', 
            'last_updated', 
            'wager', 
            'battle_rules', 
            'accepting_time', 
            'offer_expiration_time', 
            'battle_time', 
            'rake',
            'platform_description',  # add this field
        )

此外,您可以查看PEP8's naming conventions来编写优雅的Python代码。