这里我有代码,我想创建一个帖子标签或类别,当我已经创建并发送到数据库的标签时,我不想创建新标签,标签下面的代码是制作副本
float: left;
如何标记不重复?
答案 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')