在一个字段中插入多个关键字

时间:2018-07-23 17:52:12

标签: python django

我的问题是我如何在一个django字段中插入多个关键字,并在像stackoverflow标签这样的模板中显示它们。

型号:

class Jobs(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(blank=True, default='')
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    tags = ?????

2 个答案:

答案 0 :(得分:1)

在作业类(标签)和新类之间创建另一个类以及Manytomany关系

class Tags(models.Model):
    tag_name=models.CharField()

在工作班上      tags = models.ManyToManyField(Tags)

要在模板中显示,可以使用for循环等

答案 1 :(得分:1)

将其设为逗号分隔的值。

class Jobs(models.Model):
    tags = models.TextField()

    def tag_list(self):
        return self.tags.split(",")

    def add_tag(self, tag_str):
        current_tags = self.tag_list()
        current_tags.append(tag_str)
        current_tags = set(current_tags)
        new_tag_string = ",".join(current_tags)
        self.tags = new_tag_string
        # you could save the model now or let caller save it outside of this method. I suggest letting caller save the model.

    def remove_tag(self, tag_str):
        current_tags = self.tag_list()
        current_tags.remove(tag_str)
        new_tag_string = ",".join(current_tags)
        self.tags = new_tag_string
        # you could save the model now or let caller save it outside of this method. I suggest letting caller save the model.