Django ManyToOne 关系

Django ManyToOne relations

请帮我处理 ManyToOne 关系。我尝试了许多不同的变体,但它对我不起作用。例外:

IntegrityError at /admin/gallery/gallery/add/ duplicate key value violates unique constraint "gallery_gallery_galleryCategories_id_key" DETAIL: Key ("galleryCategories_id")=(1) already exists.

我的模型代码:

from django.db import models
from datetime import datetime
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill


class Gallery(models.Model):
    title = models.CharField(max_length=255, verbose_name='Title', null=True)
    galleryCategories = models.ForeignKey('GalleryCategories', verbose_name='Category', unique=False) #this line

    def __unicode__(self):
        return self.title


class GalleryCategories(models.Model):
    title = models.CharField(max_length=255, verbose_name='Title', null=True)

    def __unicode__(self):
        return self.title

请帮帮我。

尝试 运行 ./manage.py makemigrations./manage.py migrate。 我认为您使用的是 unique=True 并且在未迁移数据库的情况下将其更改为 False