首页 \ 问答 \ django-rest-framework中可写的嵌套序列化程序?(Writable nested serializer in django-rest-framework?)

django-rest-framework中可写的嵌套序列化程序?(Writable nested serializer in django-rest-framework?)

我的设计如下关于Django ModelSerializer。 有模型A和模型B.模型B有模型A的外键字段。由于某些原因,我不能直接使用主键来序列化模型B.我的想法,我需要的是序列化其他两个字段(在A型中独一无二。

我看到SlugRelatedField必须用于一个slug字段。 我搜索了一个NaturalKeyField可以支持NaturalKeyField。 但看起来它被django-rest-framework所取代。 但我检查了django-rest-framework,根本就没有这样的字段。 谁能帮忙? 我该怎么办?

代码如下。 模型A.

class AssetModel(models.Model):
    org = models.ForeignKey(Org, related_name='models')
    name = models.CharField(max_length=128)
    model_type = models.SmallIntegerField(default = 3,choices = MODEL_TYPE )
    directory = models.CharField(max_length = 128)
    ...
    class Meta:
        unique_together = ('org', 'name',)

模型B.

class Dataitem(models.Model):
    mod = models.ForeignKey(AssetModel, related_name='dataitems')
    name = models.CharField(max_length=128)
    data_type = models.SmallIntegerField(default =0,choices = DATAITEM_DATATYPE)
    ...

A型串行器

class AssetModelSerializer(serializers.ModelSerializer):
    org =  serializers.SlugRelatedField(queryset=Org.objects.all(), slug_field='name')
    class Meta:
        model = AssetModel
        fields = ('org', 'name', 'model_type',..

B型串行器

class DataitemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dataitem
        fields = ('mod', 'name','data_type'...)

模型A的主键只是Django auto添加的id。 序列化模型B时,我需要获取模型A的组织和名称。需要读取和写入。


My design is as following about Django ModelSerializer. There are model A and model B. Model B has a foreign key field of Model A. For some reasons, I can not use the primary key directly to serialize Model B. As my thought, what I need is to serialize two other fields(unique together in Model A).

And I see the SlugRelatedField must be used for one slug field. I searched there is a NaturalKeyField can support NaturalKeyField. But it looks like it is superseeded by django-rest-framework. But I checked the django-rest-framework, there is no such field at all. Can anyone help?? What should I do?

The code is as following. Model A

class AssetModel(models.Model):
    org = models.ForeignKey(Org, related_name='models')
    name = models.CharField(max_length=128)
    model_type = models.SmallIntegerField(default = 3,choices = MODEL_TYPE )
    directory = models.CharField(max_length = 128)
    ...
    class Meta:
        unique_together = ('org', 'name',)

Model B

class Dataitem(models.Model):
    mod = models.ForeignKey(AssetModel, related_name='dataitems')
    name = models.CharField(max_length=128)
    data_type = models.SmallIntegerField(default =0,choices = DATAITEM_DATATYPE)
    ...

Serializer of model A

class AssetModelSerializer(serializers.ModelSerializer):
    org =  serializers.SlugRelatedField(queryset=Org.objects.all(), slug_field='name')
    class Meta:
        model = AssetModel
        fields = ('org', 'name', 'model_type',..

Serializer of model B

class DataitemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dataitem
        fields = ('mod', 'name','data_type'...)

The primary key of Model A is just a id Django auto added. When serialize the model B, I need to get the org and name of model A. Both read and write are needed.


原文:https://stackoverflow.com/questions/34784979
更新时间:2021-10-18 11:10

最满意答案

您可以生成一系列数字,然后将该范围与所有记录交叉连接,将30天的组添加到返回的数字行。

这样的事情(没有经过测试,请原谅任何错别字): -

SELECT a.id, b.aNum, DATE_ADD(a.start_date, INTERVAL (b.aNum * 30) DAY) AS from_date, DATE_ADD(a.start_date, INTERVAL ((b.aNum + 1) * 30) DAY) AS to_date
FROM sometable a
CROSS JOIN
(
    SELECT tens.aCnt * 10 + units.aCnt AS aNum
    FROM
    (SELECT 1 AS aCnt UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) units
    CROSS JOIN
    (SELECT 1 AS aCnt UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) tens
) b
WHERE  DATE_ADD(a.start_date, INTERVAL (b.aNum * 30) DAY) <= end_date

此版本仅适用于最多100组30天,但可以轻松扩展(但是你应该处理的群体越多,速度会越慢)


You can generate a range of numbers, then cross join that range with all the records, adding as many groups of 30 days to that row as the number returned.

Something like this (not tested so please excuse any typos):-

SELECT a.id, b.aNum, DATE_ADD(a.start_date, INTERVAL (b.aNum * 30) DAY) AS from_date, DATE_ADD(a.start_date, INTERVAL ((b.aNum + 1) * 30) DAY) AS to_date
FROM sometable a
CROSS JOIN
(
    SELECT tens.aCnt * 10 + units.aCnt AS aNum
    FROM
    (SELECT 1 AS aCnt UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) units
    CROSS JOIN
    (SELECT 1 AS aCnt UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) tens
) b
WHERE  DATE_ADD(a.start_date, INTERVAL (b.aNum * 30) DAY) <= end_date

This version only works for up to 100 groups of 30 days but can easily be expanded (but will get slower the more groups you cope with)

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。