Django标签系统

时间:2018-04-07 17:26:30

标签: python django

这里我有代码,我想创建一个帖子标签或类别,当我已经创建并发送到数据库的标签时,我不想创建新标签,标签下面的代码是制作副本

float: left;

如何标记不重复?

1 个答案:

答案 0 :(得分:0)

您可以使用get_or_create方法来避免创建重复项。另外,我认为您应该将ManyToMany字段移至Post模型。

<强> models.py

from django.db import models


class Tag(models.Model):
    tag = models.CharField(max_length=50)

class Post(models.Model):
    post = models.CharField(max_length=50)
    tags = models.ManyToManyField('Tag', through="Tagging")

class Tagging(models.Model):
    posts = models.ForeignKey('Post', on_delete=models.CASCADE)
    taggings = models.ForeignKey('Tag', on_delete=models.CASCADE)

<强> views.py

from django.shortcuts import render, redirect
from .models import Post, Tag, Tagging


def index(request):
    if request.method == "POST":
        post = request.POST['post']
        tag = request.POST['tag']
        posts = Post.objects.create(post=post)
        tags, created = Tag.objects.get_or_create(tag=tag)
        tp = Tagging(posts=posts, taggings=tags)
        tp.save()
        return redirect('index')
    return render(request, 'index.html')