【问题标题】:Using ModelSerializer with joined records将 ModelSerializer 与连接记录一起使用
【发布时间】:2015-08-03 15:10:15
【问题描述】:

我正在尝试制作一个用于在网络上绘制图表的工具。我有一个这样的模型:

class PlaneableItem(Model):
    name = models.CharField(max_length=NAME_LENGTH, blank=True)

class View(PlaneableItem):
    # Some useful details

class Anchor(Model):
    view = models.ForeignKey(View)
    planeable = models.ForeignKey(PlaneableItem)

class BlockRepresentation(Anchor):
    # Useful details

class LineRepresentation(Anchor):
    # Useful details

我尝试创建一个 rest API,它返回特定视图的所有块和线的列表,包括它们所引用的可飞机的名称。

我可以使用以下方法获得一个查询集:

qs = BlockRepresentation.objects.filter(view=theview).all()
qs.select_related('planeable')
qs.extra(select={'name': 'rest_api_planeableitem.name'})

但是,现在我不能在其上使用 ModelSerializer,因为字段“名称”不是 BlockRepresentation 的一部分。

我真的很喜欢 ModelSerializers,有没有更好的方法呢?

【问题讨论】:

    标签: django python-3.x django-rest-framework


    【解决方案1】:

    您需要extra() 电话是否有特殊原因?如果该调用的唯一目的是重命名字段,则可以从查询集中省略它,并使用序列化程序中的 SerializerMethodField 重命名该字段。我将假设 planeableBlockRepresentation 模型到 PlaneableItem 模型中的 ForeignKey 字段。示例代码:

    from rest_framework import serializers
    
    class BlockRepresentationSerializer(serializers.ModelSerializer):
        # Some fields
        name = serializers.SerializerMethodField()
    
        class Meta:
            model = BlockRepresentation
    
        def get_name(self, obj):
            if obj.planeable:
                return obj.planeable.name
            return ''
    

    【讨论】:

    • 我不知道 SerializerMethodField,我试图在查询集中解决它。但这可能会!谢谢!
    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2021-06-16
    • 2012-07-30
    • 2017-11-18
    相关资源
    最近更新 更多