本文介绍了django-simple-history 中 ManyToManyField 的历史的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Story short, I need to save in the history the changes made on a Many-To-Many fields of one of my models.

I can see from: https://github.com/Kyruus/django-simple-history/commit/5ba8d2b4d72819f154a11f297796e6a2bb7172bfthat the M2M is supported. However whenever I make a change on a M2M field it changes as well in all the history, as if never has been changed. I'm new to django and python so maybe I'm missing something.

My models.py:

from django.db import models
from simple_history.models import HistoricalRecords

class Student(models.Model):
  studentname = models.CharField(max_length=50, verbose_name='Name')

class ClassRoom(models.Model):
  classname = models.CharField(max_length=50, verbose_name='Name')
  students = models.ManyToManyField(Student)
  history = HistoricalRecords()

My admin.py:

from django.contrib import admin
from school.models import Student, ClassRoom
from simple_history.admin import SimpleHistoryAdmin

class StudentAdmin(SimpleHistoryAdmin):
  list_display = ('studentname',)

class ClassRoomAdmin(SimpleHistoryAdmin):
  list_display = ('classname',)

admin.site.register(Student,StudentAdmin)
admin.site.register(ClassRoom, ClassRoomAdmin)

I installed the django-simple-history by:

>pip install django-simple-history
解决方案

This is an old open question, and might be irrelevant by now, but from looking into the code of the project in question, it seems like the last line on the ClassRoom model should be changed to

history = HistoricalRecords(m2m_fields=['students'])

这篇关于django-simple-history 中 ManyToManyField 的历史的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:53