django 如何将外键链接到模型

b5lpy0ml  于 2022-12-30  发布在  Go
关注(0)|答案(1)|浏览(109)

我有一个叫做Item的类,这个项目有时链接到Category,有时链接到SubCategory,

class Category(models.Model):
    name = models.CharField(max_length=255)
    rank = models.IntegerField()
    def __str__(self):
        return self.name

class SubCategory(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, on_delete=models.PROTECT,related_name='sub_category')
    rank = models.IntegerField()
    def __str__(self):
        return self.name

class Item(models.Model): 
    user = models.ForeignKey(User, on_delete=models.PROTECT) 
    title = models.CharField(max_length=255)
    category = models.ForeignKey(<<-- Category or subCategory -->>, on_delete=models.PROTECT,)

我需要链接项目与两个模型,所以我可以使用排序排名字段

inb24sb2

inb24sb21#

我会这样做。

class Category(models.Model):
    CAT_TYPES = [
        ('M', 'Main Category'),
        ('S', 'Sub Category'),
    ]
    name = models.CharField(max_length=255)
    type = models.CharField(max_length=1, choices=CAT_TYPES, blank=True, default='M')
    rank = models.IntegerField()
    def __str__(self):
        return self.name

class Item(models.Model): 
    user = models.ForeignKey(User, on_delete=models.PROTECT) 
    title = models.CharField(max_length=255)
    category = models.ForeignKey(Category, ...)

views.py

def something(request):
    main_categories = Categories.objects.filter(type='M')
    sub_categories = Categories.objects.filter(type='S')

相关问题