我不明白为什么这不起作用,因为在Python控制台中它对我来说很好...
class Activity(models.Model):
id = models.CharField(max_length=250, primary_key=True)
description = models.CharField(max_length=255, null=False, help_text="Brief description of the activity")
start = models.DateTimeField(default=timezone.now, verbose_name="Planned start date/time", blank=True)
end = models.DateTimeField(default=timezone.now, verbose_name="Planned completion date/time", blank=True)
class Meta:
verbose_name_plural = 'Activities'
def save(self, *args, **kwargs):
self.id = "%s-%s" % (self.description, str(self.start.date()))
super(Activity, self).save(*args, **kwargs)
def __str__(self):
"""
String for representing the Model object (in Admin site etc.)
"""
return f'{self.description}'
但是我得到的self.id字段是(使用“ xx”作为描述):
"xx-<built-in method date of datetime.datetime object at 0x000001FCBAAA51E0>"
答案 0 :(得分:1)
尝试改用strftime
def save(self, *args, **kwargs):
self.id = "%s-%s" % (self.description, self.start.strftime('%m/%d/%Y'))
super(Activity, self).save(*args, **kwargs)