Django - 一个模型中的2个外键字段(限制选项)

时间:2017-01-04 23:26:00

标签: django

我正在尝试向管理员面板添加简单选项。我有类别,子类别和网站模型。例如: 电脑(类别)     - PC(子类别)     - 笔记本(子类别) 健康(类别)     - 饮食(子类别)     - 健身(子类别) 子类别属于类别。当我在管理面板中添加网站时,我列出了所有类别和子类别。当我在我的子类别字段中选择类别(计算机)时,我有:PC,笔记本,饮食,健身(所有子类别)。我不知道如何才能将其过滤到PC和笔记本电脑。有什么建议吗?

class Category(models.Model):
    name = models.CharField(max_length=30, unique=True,
                        verbose_name='Nazwa kategorii')
    slug = models.SlugField()
    image = models.ImageField(upload_to='category_images',
                          verbose_name="Image",
                          blank=True)
    description = models.TextField(default='Description',
                               verbose_name="Category description")

class Meta:
    verbose_name_plural = "Categories"

def save(self, *args, **kwargs):
    self.slug = slugify(self.name)
    super(Category, self).save(*args, **kwargs)

def image_thumb(self):
    if self.image:
        return '<img src="/media/%s" width="40" height="40" />' % (self.image)
    else:
        return('')
image_thumb.short_description = 'Thumb'
image_thumb.allow_tags = True

def __str__(self):
    return self.name


class SubCategory(models.Model):
    category = models.ForeignKey(
        'Category',
        related_name='subcategory',
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
    name = models.CharField(max_length=30)

    class Meta:
        verbose_name_plural = "Subcategories"

    def __str__(self):
        return self.name


class Site(models.Model):
    category = models.ForeignKey('Category')
    # sub = SubCategory.objects.filter(category=category)
    subcategory = models.ForeignKey('SubCategory', related_name='subcategory')
    name = models.CharField(max_length=30)

0 个答案:

没有答案