【问题标题】:Django unique slug field for two or more models用于两个或多个模型的 Django 独特的 slug 字段
【发布时间】:2022-11-27 10:42:46
【问题描述】:

我有这样的结构:

class Category(models.Model):
    name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
    parent = models.ForeignKey('self', blank=True, null=True,
                               related_name='children',
                               on_delete=models.CASCADE
                               )
    slug = models.SlugField(max_length=255, null=False, unique=True)


class Product(models.Model):
    name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
    to_category = models.ForeignKey(Category, on_delete=models.SET_NULL,
                                    blank=True, null=True,
                                    )
    slug = models.SlugField(max_length=255, null=False, unique=True)

我创建了一个带有 slug“test”的类别。当我尝试使用 slug“test”创建新类别时,我收到警告消息,没问题。但是,如果我尝试使用 slug“test”创建产品,我不会收到警告,这对我来说并不好。是否有解决方案或方法来验证 slug 字段的产品和类别模型的唯一性?

【问题讨论】:

  • 所以你想要一个全球性的“鼻涕虫”空间?
  • 我认为这种方法是解决问题的一种选择

标签: python python-3.x django django-models


【解决方案1】:

您可以覆盖每个方法的保存方法,然后检查给定的 slug 是否已经存在于产品或类别中。

def is_slug_unique(slug):
    product_exists = Product.objects.filter(slug=slug).exists()
    category_exists = Category.objects.filter(slug=slug).exists()
    if product_exists or category_exists:
        return False
    else:
        return True

class Category(models.Model)
    ...

    def save(self, *args, **kwargs):
        slug_unique = is_slug_unique(self.slug)
        if not slug_unique:
            # do something when the slug is not unique
        else:
            # do something when the slug is unique
            super().save(*args, **kwargs)

class Product(models.Model)
    ...

    def save(self, *args, **kwargs):
        slug_unique = is_slug_unique(self.slug)
        if not slug_unique:
            # do something when the slug is not unique
        else:
            # do something when the slug is unique
            super().save(*args, **kwargs)


【讨论】:

    猜你喜欢
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多