使用OneToOneField序列化对象

时间:2018-10-09 17:03:19

标签: django python-3.x

我正在尝试将带有上下文字典的Scenes对象发送到模板。这些是模型:

class Scene1(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    number = models.IntegerField(default=0)
    name = models.CharField(max_length=20)

class Scene2(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    number = models.IntegerField(default=0)
    name = models.CharField(max_length=20)

class Scenes(models.Model):
    scene1 = models.OneToOneField(Scene1, on_delete=models.CASCADE)
    scene2 = models.OneToOneField(Scene2, on_delete=models.CASCADE)

当我这样做

queryset = Scenes.objects.filter(id=1).values()
context = {"scenes": queryset[0]}
print(queryset)

我得到:

<QuerySet [{'id': 1, 'scene1_id': 3, 'scene2_id': 3,}]>

我如何序列化数据以使Scene1和Scene2中的所有信息在上下文字典中可见?

2 个答案:

答案 0 :(得分:0)

我更喜欢在Model上添加to_dict方法。例如;

class Scene1(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    number = models.IntegerField(default=0)
    name = models.CharField(max_length=20)
    def to_dict():
        return {'timestamp': self.timestamp.isoformat(), 'number': self.number,'name': self.name}

class Scene2(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    number = models.IntegerField(default=0)
    name = models.CharField(max_length=20)
    def to_dict():
        return {'timestamp': self.timestamp.isoformat(), 'number': self.number,'name': self.name}

class Scenes(models.Model):
    scene1 = models.OneToOneField(Scene1, on_delete=models.CASCADE)
    scene2 = models.OneToOneField(Scene2, on_delete=models.CASCADE)
    def to_dict():
        return {'scene1': self.scene1.to_dict(), 'scene2': self.scene2.to_dict()}

答案 1 :(得分:0)

我最终使用了这些序列化器:

from rest_framework import serializers

class Scene1Serializer(serializers.ModelSerializer):
    class Meta:
        model = Scene1
        fields = ('name',)

class Scene2Serializer(serializers.ModelSerializer):
    class Meta:
        model = Scene2
        fields = ('name',)


class ScenesDetailSerializer(serializers.ModelSerializer):
    scene1 = Scene1Serializer()
    scene2 = Scene2Serializer()

    class Meta:
        model = Scenes
        fields = ('scene1', 'scene2')

然后在我看来:

queryset = Scenes.objects.filter(id=1)
scenes = queryset[0]
scenes_serialized = ScenesDetailSerializer(scenes)
data = scenes_serialized.data
print(data) # prints: {'scene1': OrderedDict([('name', some_name_1)]), 'scene2': OrderedDict([('name', some_name_2)])

context = {"scenes": data}

现在在模板中,我可以使用点表示法来获取名称变量:

{{ scenes.scene1.name }}
{{ scenes.scene2.name }}