【问题标题】:How to write model for tags database如何为标签数据库编写模型
【发布时间】:2014-09-26 10:11:10
【问题描述】:

我想创建一个带有标签和类别的对象。我在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)

将创建大量标签,并将其用于项目的搜索关键字。不确定这是否是最好的解决办法。

【问题讨论】:

  • 为什么不使用django-tagit?至少你可以看看他们的models.py,看看如何设置模型进行标记。
  • 我是 django 新手,有很多东西我不知道。不过谢谢推荐,会考虑的。

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


【解决方案1】:

根据您的任务描述(一个项目只能有一个类别和多个标签。标签也与类别中的/组相关联。)我建议以下架构:

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 字段。

【讨论】:

    猜你喜欢
    • 2011-02-13
    • 2011-04-15
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2016-03-30
    • 1970-01-01
    相关资源
    最近更新 更多