Slug Field in Django Model Not Including Related Tags on Save
I have the following save
method in my Django model:
slug = models.SlugField(unique=True, blank=True, null=True, max_length=255)
def save(self, *args, **kwargs):
if self.pk is None:
super().save(*args, **kwargs)
tags = Tag.objects.filter(office__id=self.id).values_list("name", flat=True)
print("Tags")
print(tags)
location_work_override_id = self.location_work_override.id if self.location_work_override else ''
location_work_id = self.contest.location_work_id if self.contest and self.contest.location_work_id else ''
if not self.slug and tags:
self.slug = slugify(
f"{self.display_name}-{'-'.join(tags)}-{location_work_override_id}-{location_work_id}-{self.contest.short_name}-{self.contest.contest_number}"
)
elif not self.slug:
self.slug = slugify(
f"{self.display_name}-{location_work_override_id}-{location_work_id}-{self.contest.short_name}-{self.contest.contest_number}"
)
super().save(*args, **kwargs)
The slug
field is supposed to include related Tag
names from a Tag
model that has a ForeignKey to Office
. However, when I create a new Office
instance in the Django admin, the tags
variable in the save
method is always empty, even though I add the tags in the admin interface.
I suspect this is a timing issue because the save
method of Office
runs before the related Tag
objects are saved.
My Questions:
- How can I ensure that the
Tag
objects are saved before thesave
method of theOffice
model accesses them? - Is there a way to correctly populate the
slug
field with the tags in this scenario, preferably without relying on manual order of operations?
I’m looking for a robust solution that works reliably in the Django admin and elsewhere.