哪个模型字段类型适合重复保存在数据库中并需要显示为字符串的日期-时间对象



这个问题有点模棱两可,请允许我解释一下:

我正在创建一个类似于变更日志的东西,它会记录创建对象的日期和时间以及创建的对象。当对象在数据库中更新时,我将获得日期时间的快照,并记录新更改的对象以及当前的&新的日期时间-对象+日期时间的先前快照也已存储。下面是一个我试图在网站上以文本形式显示的"变更日志"的例子:

Oct. 24, 2017, 11:22 a.m  
"Cats and dogs", "Apples and oranges"  
Oct. 19, 2017, 12:04 p.m  
"This is a string object", "This is the second object/preference"  
Sep. 03, 2017, 01:22 a.m   
"This object was saved long ago", "As was this one" 

因此,问题有两个方面——哪些模型字段类型适合需要记录当前日期时间的对象,以及如何将以前的变更日志作为文本保存在数据库中中,而不仅仅是查询最近的一个?

在以下失败的尝试中,Profile模型包含要更改和记录的对象/"首选项",以及用于保存对象时保存当前日期时间的updated字段。计划是在保存对象后发送一个信号,该信号将调用get_preference()类方法,该方法返回要记录的对象的元组。这将通过postrongave信号保存到old_preferences属性上,该信号将在视图中查询并作为变更日志的一部分发送到模板。

根据我的理解,当我更新表单时,它应该会导致save(),从而触发信号
唉,它根本不起作用,我也不知道为什么它不起作用。

class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True, blank=True)
preference1 = models.CharField(max_length=54, blank=True, null=True)
preference2 = models.CharField(max_length=54, blank=True, null=True)  
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
old_preferences = models.CharField(max_length=300)
@classmethod
def get_preference(cls):
preference_set = cls.preference1, cls.preference2
return preference_set

def profile_post_save_receiver(sender, instance, created, *args, **kwargs):
if instance:
Profile.objects.old_preferences = Profile.get_preference()
post_save.connect(profile_post_save_receiver, sender=Profile)  

此外,以下是视图、表单和模板的相关部分

视图:

class PreferenceUpdateView(LoginRequiredMixin, UpdateView):
form_class = PreferenceUpdateForm
template_name = 'profile/preference_edit.html'
def get_object(self, *args, **kwargs):
# print(self.kwargs)
user_profile = self.kwargs.get('username')
# user_profile = self.kwargs.get('id')
obj = get_object_or_404(Profile, user__username=user_profile)
return obj
def form_valid(self, form):
print(self.kwargs)
instance = form.save(commit=False)
instance.user = self.request.user
return super(PreferenceUpdateView, self).form_valid(form)  

模板:

{{object.updated}}
{{object.old_preferences}}

形式:

from .models import Profile
from django import forms
class PreferenceUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
"preference1",
"preference2",
]

编辑:如果我需要进一步澄清这个问题,请告诉我

也许我没有正确理解您想要实现的目标,但这看起来是一种非常复杂的方法。为什么不将旧配置文件作为数据集保留在配置文件中?您只需更改与ManyToOne的关系,并在UpdateView中确保您只阅读最新的个人资料:

型号

class Profile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True, blank=True)

from django.http import Http404

查看

class PreferenceUpdateView(LoginRequiredMixin, UpdateView):
form_class = PreferenceUpdateForm
template_name = 'profile/preference_edit.html'
def get_object(self, *args, **kwargs):
user_profile = self.kwargs.get('username')
try:
obj = Profile.objects.filter(user__username=user_profile).latest('updated')
return obj
except Profile.DoesNotExist:
raise Http404

最新更新