问题
I have created this model in Django which also saves date and slug. But even if I am making these changes again the str and the slug still remains the same and not updating as per the new data. How to fix this ?
class EntranceExamination(models.Model):
course = models.CharField(max_length=100, blank=True, default='')
year = models.PositiveIntegerField(choices=year_choices(),default=current_year(), validators=[MinValueValidator(1984), max_value_current_year])
month = models.PositiveIntegerField(choices=month_choices(),validators=[MinValueValidator(1), MaxValueValidator(12)])
day = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(31)])
start_time = models.TimeField(blank=True)
end_time = models.TimeField(blank=True)
slug = models.SlugField(editable=False,max_length=100)
class Meta:
ordering = ['month']
def __str__(self):
return f"{self.course}'s exam on {self.slug}"
def save(self):
if not self.slug:
self.slug = f'{self.day}-{self.month}-{self.year}'
super(EntranceExamination, self).save()
回答1:
__str__
is evaluated when you can str(…)
on the object, so when data on the model changes, then __str__
will return something different.
As for slug, you can each time update the slug when you save the model:
class EntranceExamination(models.Model):
# …
def save(self, *args, **kwargs):
self.slug = f'{self.day}-{self.month}-{self.year}'
super().save(*args, **kwargs)
This will however not work when you update in bulk through the ORM, since ORM calls often circumvent the .save(…)
method and triggers.
It is however not a good idea. Slugs are used for URI's, and as the W3 consortium says: "Cool URIs don't change" [w3.org]:
When you change a URI on your server, you can never completely tell who will have links to the old URI. They might have made links from regular web pages. They might have bookmarked your page. They might have scrawled the URI in the margin of a letter to a friend.
When someone follows a link and it breaks, they generally lose confidence in the owner of the server. They also are frustrated - emotionally and practically from accomplishing their goal.
Enough people complain all the time about dangling links that I hope the damage is obvious. I hope it also obvious that the reputation damage is to the maintainer of the server whose document vanished.
来源:https://stackoverflow.com/questions/65267519/how-to-update-str-and-slug-everytime-after-djangos-model-update