简体   繁体   中英

PRIMARY KEY must be unique error (Django)

->'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)

When i make a post to the above view i get ' PRIMARY KEY must be unique' . What am i doing wrong? This is the line "album = event" which causes the error.

Final solution after correction:

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)

From chat with Monique: the problem is in the (non-posted) Photo.save() method that makes two calls to super().save() , passing the same args in both cases , so the first call correctly creates the Photo instance and the second tries to insert it again, which obviously fails.

Solution (for anyone having the same problem): dont blindly pass *args and **kwargs to Model.save() when your overload it and end up calling it a second time.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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