我有以下摘要:
class A:
clientname ...
logs = models.ManyToManyField(B, blank=True, null=True)
class B.
message ...
timestamp = models.DateTimeField()
def save(self, *args, **kwargs):
self.timestamp = datetime.now()
super(B, self).save(*args, **kwargs)
现在,如果保存了一条消息,我希望它始终具有时间戳。我不想改变很多关系。这可能吗?如果是这样我会怎么写呢?
更新:
我的观点
def log(request):
if request.method == 'POST':
log, created = B.objects.get_or_create(message=request.POST['message'])
client = \
A.objects.get(clientname=request.POST['clientname'])
client.logs.add(log)
return HttpResponse(content="OK", mimetype="text/plain", status=200)
else:
return HttpResponse(content="Failed", mimetype="text/plain", status=400)
RESOLUTON: 我做到了,这是一种解决方法:
def log(request):
if request.method == 'POST':
time = datetime.now()
log, created = \
Log.objects.get_or_create(message=request.POST['message'], \
timestamp=time)
client = \
Thinclient.objects.get(hostname=request.POST['clientname'])
client.logs.add(log)
return HttpResponse(content="OK", mimetype="text/plain", status=200)
else:
return HttpResponse(content="Failed", mimetype="text/plain", status=400)
更新:
实际上并不是我想要的,因为这会创建新的消息实例,即使消息是相同的
答案 0 :(得分:1)
您可以将DateTimeField
与auto_now
参数一起使用:
timestamp = DateTimeField(auto_now=True)
更多相关信息: https://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.DateField.auto_now
答案 1 :(得分:0)
将save()添加到B类
def save(self, *args, **kwargs):
self.timestamp = datetime.now()
super(B, self).save(*args, **kwargs)