我有1个充当主要表单的ModelAdmin和2个与之配套的admin.TabularInlines。当通过一个名为RoomList的单独模型通过多对多关系保存CleaningLog时,我试图用数据预填充CleaningEntryInline。
因此,我应该从CleaningAction模型中选择带有FK的所有记录,并将其用作EntryInline中的FK引用,但是每当我尝试保存它时,都会引发错误,但不提供任何回溯。据我了解,您需要重写save_formset()方法,但实际上并不知道从那里去。任何帮助将是救生员!
class CleaningActionAdmin(admin.ModelAdmin):
list_display = ['room', 'action']
list_filter = ['room']
class CleaningEntryInline(admin.TabularInline):
model = CleaningEntry
extra = 0
autocomplete_fields = ['cleaning_item']
fieldsets = [
(None,{'fields':[('cleaning_item', 'checked', 'na', 'grade', 'notes')]})
]
class CleaningLogAdmin(admin.ModelAdmin):
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
pre_instance = form.save(commit=False)
get_actions = EquipmentAction.objects.filter(machine_action_id=pre_instance.cleaned_machine_id)
# This is where I'm lost...
for action in get_actions:
new_action, is_new_action = CleaningEntry.objects.update_or_create(
log_entry_id=pre_instance.id,
cleaning_item_id=action.id
)
new_action.save()
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
instance.save()
formset.save_m2m()
def save_model(self, request, obj, form, change):
obj.auditor = request.user.username
obj.save()
ordering = ('-start_time',)
list_display = ['room_cleaned', 'order_cleaned', 'start_time', 'clean_time','cleaning_users','auditor']
list_filter = ['stop_time', 'room_cleaned']
fieldsets = [
('Cleaning Info',{'fields':[('room_cleaned', 'order_cleaned')]}),
(None,{'fields':[('start_time')]}),
(None,{'fields':[('clean_time','auditor')]})
]
inlines = [CleaningUserInline, CleaningEntryInline]