如何临时禁用Django模型之间的ForeignKey关系

时间:2018-09-03 20:46:58

标签: python django django-models

class Season(models.Model):
    """
    unique season object  per clothing drop
    """
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to='season', blank=True)
    season_available = models.BooleanField(default=True)

    class Meta:
        """
        meta-data per season
        """
        ordering = ('name',)
        verbose_name = 'season'
        verbose_name_plural = 'seasons'

    def __str__(self):
        return '{}'.format(self.name)

我想只与“类别iff服装(类别)”相关的课程季节

class Category(models.Model):
    """
    categories for products
    """
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    season = models.ForeignKey(Season, on_delete=models.CASCADE)

    class Meta:
        """
        meta-data per category
        """
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'
    def foreign_key_controller(self):
        """enable foreign key relationship with specific models."""


    def __str__(self):
        """

        :return: '{}'.format.(self.name)
        :rtype: str
        """
        return '{}'.format(self.name)

所有产品的类别类别,不包括在服装中。

class Apparel(models.Model):
    """
    unique product per category per season
    """
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(decimal_places=2, max_digits=10)
    image = models.ImageField(upload_to='product', blank=True)
    stock = models.IntegerField()
    product_available = models.BooleanField(default=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_latest_update = models.DateTimeField(auto_now=True)

在这里,我想使用if / else创建一个函数,以在Category()!= Apparel中的外键时禁用Season和Category之间的外键关系。

    class Meta:
        """
        meta-data for product
        """
        ordering = ('name',)
        verbose_name = 'product'
        verbose_name_plural = 'products'

    def __str__(self):
        """
        readable representation of class
        :return:
        :rtype: str
        """
        return '{}'.format(self.name )

基本上,我只希望各个季节能够拥有不同类型的服装。另外,如果您想知道,除了服装,我没有列出其他任何涉及类别的模型,但是在这种情况下,有这样的模型。例如,一个名为Music的类可能与Category具有ForeignKey关系,因此,如果Category引用Music,则类别和季节之间的外键关系将被禁用。

我最初只是想创建一个类似于Category的单独的类,但只与商店中与服装无关的商品有关系,与Season无关,但是应该有更好的方法吗?

谢谢!

0 个答案:

没有答案