PRIMARY KEY必须是唯一错误(Django)

时间:2013-12-23 10:49:59

标签: python django views primary-key

- > 'views.py':

def upload_event_image(request):
  if request.method=="POST":
    if request.FILES:
      fest=get_object_or_404(Fest, pk=request.POST.get('fest_pk'))
      if fest is not None:
        event = Event.objects.create(
          author = request.user,
          fest = fest,
        )
        event.save()
        if event:
          photo= Photo.objects.create(
            image = request.FILES['file'],
            album = event //This line causes the error
          )
          photo.save()
        return HttpResponse()
  return HttpResponse()

- > model.py:

class Event(models.Model):
    title = models.CharField(max_length=60, blank=True)
    description = models.TextField(blank = True)
    fest = models.ForeignKey(Fest)
    pub_date = models.DateTimeField(default=datetime.datetime.now)
    author = models.ForeignKey(User)

    def __unicode__(self):
        return self.description

    def has_upvoted(self, user):
        return user

class Photo(models.Model):
    title = models.CharField(max_length=60 , blank= True, null = True)
    image = models.ImageField(upload_to='site-media/media/images/')
    thumbnail = models.ImageField(upload_to="site-media/media/images/thumbs/", blank=True, null=True)
    thumbnail2 = models.ImageField(upload_to="site-media/media/images/thumbs2/", blank=True, null=True)
    pub_date = models.DateTimeField(auto_now_add=True)
    album = models.ForeignKey(Event)

当我在上面的视图中发帖时,我得到' PRIMARY KEY必须是唯一的'。我究竟做错了什么? 这是导致错误的“album = event”行。

纠正后的最终解决方案:

def save(self, force_insert=False, force_update=False, **kwargs):
    """Save image dimensions."""
    super(Photo, self).save(force_insert, force_update, **kwargs)
    im = PImage.open(pjoin(MEDIA_ROOT, self.image.name))
    self.width, self.height = im.size

    self.create_thumbnail()
    force_insert = False
    force_update = True

    super(Photo, self).save(force_insert, force_update, **kwargs)

1 个答案:

答案 0 :(得分:3)

与Monique聊天:问题在于(非发布)Photo.save()方法,该方法对super().save()进行两次调用,在两种情况下传递相同的args ,所以第一次调用正确地创建了Photo实例,第二次尝试再次插入它,这显然失败了。

解决方案(对于遇到相同问题的任何人):不要在您超载时盲目地将*args**kwargs传递给Model.save()并最终将其称为第二次。

class Foo(models.Model):
    def save(self, force_insert=False, force_update=False, **kwargs):
        super(Foo, self).save(force_insert, force_update, **kargs)
        if somethings_needs_to_be_done:
            do_something_here()
            super(Foo, self).save(force_insert=False, force_update=True, **kwargs)