django-rest-framework:为外键设置序列化程序

时间:2014-08-08 11:14:11

标签: django django-rest-framework

在我的模型中,我有两个名为VtableVdata的表。每个虚拟表(在Vtable中)都包含存储在Vdata中的虚拟数据条目。

我正在尝试制作一个视图,显示与Vdata对应的Vtable列表

我的序列化程序无法运行,我认为这是因为我正在倒退。 我认为问题出在这一行: table_id = serializers.RelatedField(many=True)

作为参考,我收到此错误:'Vtable' object is not iterable

这是我的models.py:

from django.db import models
from django.contrib.auth.models import User

class Vtable(models.Model):
    user = models.ForeignKey(User)
    table_name = models.CharField(max_length=200)
    added_date = models.DateTimeField('date added')
    def __unicode__(self):
        return self.table_name

class Vdata(models.Model):
    table_id = models.ForeignKey(Vtable)
    table_pk = models.IntegerField()
    column_1 = models.CharField(max_length=200)
    column_2 = models.CharField(max_length=200)
    added_date = models.DateTimeField('date added')
    def __unicode__(self):
        return str(self.added_date)

这是我的serializers.py:

from django.contrib.auth.models import User, Group
from rest_framework import serializers
from vtables.models import Vtable, Vdata

class TableSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.Field(source='user.username')

    class Meta:
        model = Vtable
        fields = ('table_name', 'added_date', 'user')

class EntrySerializer(serializers.HyperlinkedModelSerializer):
    table_id = serializers.RelatedField(many=True)

    class Meta:
        model = Vdata
        fields = ('table_id', 'table_pk', 'column_1', 'column_2', 'added_date')

以下是调用它的视图:

class EntryList(APIView):
    def get(self, request, format=None):
        entries = Vdata.objects.all()
        serializer = EntrySerializer(entries, many=True)
        return Response(serializer.data

        class Meta:
            model = Vdata
            fields = ('table_id', 'table_pk', 'column_1', 'column_2', 'added_date')

1 个答案:

答案 0 :(得分:8)

以下是如何执行此操作的示例:

class TableSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.Field(source='user.username')
    entries = EntrySerializer(many=True)

    class Meta:
        model = Vtable
        fields = ('table_name', 'added_date', 'user', 'entries')

class EntrySerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Vdata
        fields = ('table_id', 'table_pk', 'column_1', 'column_2', 'added_date')

对于观点:

class EntryList(GenericAPIView):
    queryset = Vtable.objects.all()
    serializer_class = TableSerializer

不要忘记:

在模型外键字段定义中设置related_name='entries'