简体   繁体   English

唯一约束失败:django 中的 post_author.href

[英]UNIQUE constraint failed: post_author.href in django

I will create a different author table using the user table available in django and I want to combine this custom table I created with the column in the post model.我将使用 django 中可用的用户表创建一个不同的作者表,我想将我创建的这个自定义表与帖子模型中的列结合起来。 Thus, I will have both the author table and the post table with the posts shared by these authors separately.因此,我将同时拥有作者表和帖子表,其中包含这些作者分别共享的帖子。 And also, I will make the user models that I will create in the future with the ready user table.而且,我将使用准备好的用户表制作我将在未来创建的用户模型。 but I am getting the error I mentioned.但我收到了我提到的错误。 When i add authors to admin panel I get this error.当我将作者添加到管理面板时,出现此错误。 When I add 1 author, there is no problem, but when I add 2nd author, I get this error.当我添加 1 个作者时,没有问题,但是当我添加第二个作者时,出现此错误。 How can I solve this, what are the alternative ways?我该如何解决这个问题,有哪些替代方法?

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.urls import reverse
from .utils import get_read_time
from django.conf import settings
from django.utils import timezone
from markdown_deux import markdown
from django.utils.text import slugify
from django.contrib.auth.models import User
from django.db.models.signals import pre_save
from django.utils.safestring import mark_safe

class GENDER(models.TextChoices):

    Erkek = "Erkek"
    Kadın = "Kadın"
    Diğer = "Diğer"
    NONE = "Belirtmek İstemiyorum"


class Category_Choices(models.TextChoices):
    BİLİNMEYENLER = '13İlinmeyenler'
    KİŞİSEL_GELİŞİM = 'Kişisel Gelişim'
    İLHAM_AL = 'İlham Al'
    YATIRIM_HABERLERİ = 'Yatırım Haberleri'
    GİRİŞİMCİLİK = 'Girişimcilik'
    ENGLİSH_NEWS = 'English News'
    BAŞARI_HİKAYELERİ = "Başarı Hikayeleri"


class Color_Choices(models.TextChoices):
    INDIGO = 'indigo'
    green = 'green'
    yellow = 'yellow'
    RED = 'red'
    blue = 'blue'
    gray = 'gray'
    pink = "pink"



class Author(models.Model):

    author = models.ForeignKey(User, on_delete = models.CASCADE)
    firstName = models.CharField(max_length=80)
    lastName = models.CharField(max_length=80)
    email = models.EmailField(null=True,blank=True)
    displayName = models.CharField(max_length=100)
    gender = models.TextField(blank=False,choices=GENDER.choices)
    avatar = models.ImageField(upload_to="avatar")
    href = models.SlugField(unique=True,editable=False)
    desc = models.TextField()
    jobName = models.CharField(default="Yazar",max_length=30)
    bgImage = models.ImageField(null=True, blank=True, upload_to="background")

    def __str__(self):
        return self.displayName

    def get_slug(self):
        href = slugify(self.displayName.replace("ı","i"))
        unique = href
        number = 1

        while Author.objects.filter(slug=unique).exists():
            unique = "{}-{}" .format(href,number)
            number += 1

        return unique




class Categories(models.Model):

    name = models.CharField(max_length=50,choices=Category_Choices.choices,default=Category_Choices.BİLİNMEYENLER)
    color = models.CharField(max_length=30,choices=Color_Choices.choices, default=Color_Choices.RED)
    href = models.SlugField(unique=True,editable=False)
    thumbnail = models.ImageField(upload_to="postpost",null=True,blank=True)

    def __str__(self):
        return self.name

    def get_category_slug(self):
        slug = slugify(self.name.replace("ı","i"))
        unique = slug
        number = 1

        while Categories.objects.filter(slug=unique).exists():
            unique = "{}-{}" .format(slug,number)
            number += 1

        return unique
    def save(self, *args, **kwargs):
        self.href = slugify(self.name)
        super(Categories,self).save(*args, **kwargs)

    def get_absolute_url(self):
        return self.href

class Post(models.Model):

    authorId = models.ManyToManyField(Author)
    title = models.CharField(max_length=255)
    desc = models.CharField(max_length=255)
    categoryID = models.ForeignKey(Categories,on_delete=models.CASCADE,)
    content = models.TextField(blank=False)
    href = models.SlugField(unique=True,editable=False)
    draft = models.BooleanField(default=True)
    readingtime = models.IntegerField(default=0)
    updated = models.DateTimeField()
    date = models.DateTimeField(editable=False,null=True)
    published = models.DateField(default=timezone.now)
    featuredimage = models.ImageField(null=True, blank=True, upload_to='post')




    class Meta:
        ordering = ['-date', '-updated']

    def __str__(self):
        return self.title

    def get_slug(self):
        slug = slugify(self.title.replace("ı","i"))
        unique = slug
        number = 1

        while Post.objects.filter(slug=unique).exists():
            unique = "{}-{}" .format(slug,number)
            number += 1

        return unique
    #@property
    #def comments(self):
    #    instance = self
    #    qs = Comment.objects.filter_by_instance(instance)
    #    return qs


    def get_markdown(self):
        content = self.content
        markdown_text = markdown(content)
        return mark_safe(markdown_text)


def pre_save_receiver(sender, instance, *args, **kwargs):
    if not instance.href and instance.title:
        instance.href = slugify(instance.title)
    if instance.content:
        html_string = instance.get_markdown()
        read_time_var = get_read_time(html_string)
        instance.read_time = read_time_var






pre_save.connect(pre_save_receiver, sender=Post)

and this error和这个错误

IntegrityError at /adminpost/author/add/
UNIQUE constraint failed: post_author.href
Request Method: POST
Request URL:    http://127.0.0.1:8000/adminpost/author/add/
Django Version: 3.2.8
Exception Type: IntegrityError
Exception Value:    
UNIQUE constraint failed: post_author.href

It seems that you try to make a create with a title that already exists.似乎您尝试使用已存在的标题进行创建。 Thus your href field isn't unique anymore.因此,您的 href 字段不再是唯一的。

Either also make the title field unique or you can add some random number identifier to your slug.也可以使title字段唯一,或者您可以向您的 slug 添加一些随机数标识符。

import uuid

def pre_save_receiver(sender, instance, *args, **kwargs):
    if not instance.href and instance.title:
        if not Post.objects.filter(href=slugify(instance.title)).exists():
            instance.href = slugify(instance.title)
        else:
            instance.href = slugify(instance.title) + str(uuid.uuid4())[:8]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM