[Answered ]-Override Django Admin Save Model

0👍

Thanks to all answers from contributors below,

I managed to fix the issues with @Mahammadhusain answer regarding making extra object.

@admin.register(AvailableHours)
class AvailableHoursAdmin(admin.ModelAdmin):
    #form = TimeGenerator
    
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)

        frm = obj.free_hours_from
        to = obj.free_hours_to
        date =obj.free_date
        # Ensure from-to range is valid and create objects within the range
        if frm is not None and to is not None:
            items = [
                AvailableHours(
                    free_date=obj.free_date,
                    status=obj.status,
                    free_hours_from=hour,
                    free_hours_to=hour + 1,
                )
                for hour in range(frm, to)
            ]
            AvailableHours.objects.bulk_create(items)
            
            extra = AvailableHours.objects.get(
                free_hours_from = frm ,
                free_hours_to = to ,
                free_date=date ,
                )
            extra.delete()

1👍

To prevent creating an additional object that spans the entire range, you can modify the logic to exclude the upper limit in the range.

from django.contrib import admin
from .models import AvailableHours

class AvailableHoursAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)

        frm = obj.free_hours_from
        to = obj.free_hours_to

        # Ensure 'from' is before 'to' and create objects within the range
        if frm is not None and to is not None and frm < to:
            range_limit = min(to, frm + 24)  # Limit the range to 24 hours max
            items = [
                AvailableHours(
                    free_date=obj.free_date,
                    status=obj.status,
                    free_hours_from=hour,
                    free_hours_to=min(hour + 1, range_limit),  # Limit 'to' within the range_limit
                )
                for hour in range(frm, range_limit)
            ]
            AvailableHours.objects.bulk_create(items)

admin.site.register(AvailableHours, AvailableHoursAdmin)

updated code uses range(frm, to) in the list comprehension, which creates objects from free_hours_from up to, but excluding, free_hours_to. Thus, it avoids creating an extra object that spans the entire range specified by the free_hours_from and free_hours_to fields.

Leave a comment