Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

python - Update SerializerMethodField in Django REST Framework

I have a serializer+models like this:

class Dates(models.Model):
    date: date = models.DateField(verbose_name='Datum')
    indicator: str = models.CharField(max_length=1, null=True, default=None, blank=True, verbose_name='Indikator')
    entry: Entry = models.ForeignKey(Entry, on_delete=models.PROTECT, related_name='dates')

class Entry(models.Model):
    pass

class EntrySerializer(serializers.ModelSerializer):
    bookings = SerializerMethodField()  # implicitly `get_dates`

    class Meta:
        model = Entry
        fields = (
            'id', 'dates',
        )
        read_only_fields = ('id',)

    def get_dates(self, instance):
        try:
            start = self.context.request.query_params.get('start')
            start = datetime.strptime(start, '%Y%m%d')
        except:
            start = None

        d = {
            date.strftime('%Y%m%d'): indicator
            for (date, indicator)
            in instance.dates.all().values_list("date", "indicator")
        }

        dates = date_range(start) # just returns a list of dates
        for date in dates: d.setdefault(date.strftime('%Y%m%d'), '')

        return d

I am using SerializerMethodField to create empty "padding" dates, should an Entry not have a Date object assigned for a certain date within the given date range. The output JSON looks like this:

[
    {
        "id": 1,
        "bookings": {
            "20210203": "D",   # actual `Date` for `Entry` object
            "20210204": "D",  # actual `Date` for `Entry` object
            "20210205": "2",  # actual `Date` for `Entry` object
            "20210201": "",  # padding dates until the end, because
            "20210202": "",  # [...] the `Entry` does not yet have an
            "20210206": "",  # [...] associated `Date` for that date yet
            "20210207": "",
            "20210208": "",
            "20210209": "",
            "20210210": "",
            "20210211": "",
            "20210212": "",
            "20210213": "",
            "20210214": "",
            "20210215": "",
            "20210216": "",
            "20210217": "",
            "20210218": "",
            "20210219": "",
            "20210220": "",
            "20210221": "",
            "20210222": "",
            "20210223": "",
            "20210224": "",
            "20210225": "",
            "20210226": "",
            "20210227": "",
            "20210228": ""
        },
    },
    ...
]

I am trying to now actually create a Date object, when the corresponding value is set on one of the dates. Likewise update if when one of the values change on an already existing Date.

Any idea on how to do that? Unfortunately the structure has to be this flat, because Datatables Editor cannot work with list-nested objects.


Clarification on the DataTables structure causing me having to add empty padding dates:

var table = $('#plan').DataTable({
    ajax: {
        url: "/api/entries/?format=datatables",
    },
    rowId: 'id',
    order: [[0, 'asc']],
    columns: [
        {
            data: 'order',
            className: 'reorder',
        },
        {data: "entry.id"},
        {data: "dates.20210201", orderable: false, priority: 5},
        {data: "dates.20210202", orderable: false, priority: 5},
        {data: "dates.20210203", orderable: false, priority: 5},
        {data: "dates.20210204", orderable: false, priority: 5},
        {data: "dates.20210205", orderable: false, priority: 5},
        {data: "dates.20210206", orderable: false, priority: 5},
        {data: "dates.20210207", orderable: false, priority: 5},
        {data: "dates.20210208", orderable: false, priority: 6},
        {data: "dates.20210209", orderable: false, priority: 6},
        {data: "dates.20210210", orderable: false, priority: 6},
        {data: "dates.20210211", orderable: false, priority: 6},
        {data: "dates.20210212", orderable: false, priority: 6},
        {data: "dates.20210213", orderable: false, priority: 6},
        {data: "dates.20210214", orderable: false, priority: 6},
        {data: "dates.20210215", orderable: false, priority: 7},
        {data: "dates.20210216", orderable: false, priority: 7},
        {data: "dates.20210217", orderable: false, priority: 7},
        {data: "dates.20210218", orderable: false, priority: 7},
        {data: "dates.20210219", orderable: false, priority: 7},
        {data: "dates.20210220", orderable: false, priority: 7},
        {data: "dates.20210221", orderable: false, priority: 7},
        {data: "dates.20210222", orderable: false, priority: 8},
        {data: "dates.20210223", orderable: false, priority: 8},
        {data: "dates.20210224", orderable: false, priority: 8},
        {data: "dates.20210225", orderable: false, priority: 8},
        {data: "dates.20210226", orderable: false, priority: 8},
        {data: "dates.20210227", orderable: false, priority: 8},
        {data: "dates.20210228", orderable: false, priority: 8},
    ]
});
question from:https://stackoverflow.com/questions/66054473/update-serializermethodfield-in-django-rest-framework

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...