gpt4 book ai didi

python - Django : how to define a unique slug for an abstract model and its children?

转载 作者:行者123 更新时间:2023-11-28 19:25:25 26 4
gpt4 key购买 nike

我有一个抽象模型,其中包含我的模型的公共(public)字段,但是如何定义一个唯一的 slug,因为我不能对抽象模型进行查询,只能对其子类进行查询?

我正在寻找一种干净简单的方法,无需手动提及子类的名称。

class MainModel(models.Model):
title = models.CharField(_('title'), max_length=150)
slug = models.SlugField(_('slug'), unique=True, max_length=150)
category = models.ForeignKey('Category', verbose_name=_('category'))

class Meta:
abstract = True

def save(self, *args, **kwargs):
# define unique slug for ChildModel1, ChildModel2

class ChildModel1(MainModel):
active = models.BooleanField()

class ChildModel2(MainModel):
content = models.TextField()

最佳答案

您可以尝试使用模型的 verbose_name :

def save(self, *args, **kwargs):
# fill in make_slug yourself
self.slug = make_slug(self._meta.verbose_name)

关于python - Django : how to define a unique slug for an abstract model and its children?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com