如何为标签数据库编写模型

时间:2014-08-03 23:53:23

标签: django database-design django-models database-schema

我想创建一个带有标签和类别的对象。我在https://stackoverflow.com/a/20871上看到标签架构应该是这样的,

> Table: Item Columns: ItemID, Title, Content
> 
> Table: Tag Columns: TagID, Title
> 
> Table: ItemTag Columns: ItemID, TagID

但是,我想将每个标签与一个类别相关联。 我想要的是一个项目只能有一个类别和多个标签。标签也与类别中的/组相关联。

我不太清楚如何使用模型关系,这就是我想出的:

class Item(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(blank=True)

class Tags(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)

class ItemTag(models.Model):
    itemid = models.ForeignKey(Item) #not sure if this is correct to use foreignkey
    tagid = models.ForeignKey(Tags)

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)

#not sure how to do this category grouping
class CategoryTags(models.Model):
    catid = models.Foreignkey(Category)
    tagid = models.Foreignkey(Tags)

将创建大量标签,并将在项目的搜索关键字中使用。不确定这是否是应对的最佳选择。

1 个答案:

答案 0 :(得分:0)

基于您的任务描述(一个项目只能有一个类别和多个标签。而且标签也与该类别中的/ group相关联。)我建议使用以下模式:

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)

class Tag(models.Model):
    name = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(unique=True)
    # the tag belongs to a category
    category = models.ForeignKey(Category, blank=True)

class Item(models.Model):
    title = models.CharField(max_length=100, db_index=True)
    content = models.TextField(blank=True)
    # the item belongs to one category 
    # if having a category is required please remove blank=True
    category = models.ForeignKey(Category, blank=True) 
    tags = models.ManyToManyField('Tag')

ForeignKey是多对一的关系。在您的情况下,许多项目属于一个类别。

另见ManyToMany字段。

相关问题