Django管理员确实更新而不是插入

时间:2014-03-19 18:37:01

标签: django django-models django-views

我的模型如下:

class Station(models.Model):
     sid = models.IntegerField(primary_key=True)
     uid = models.ForeignKey('User', db_column='uid', verbose_name='User')
     name = models.CharField(max_length=100)
     # and others...     
class Meta:
    managed = False
    db_table = 'Stations'

class Playlist(models.Model):
    plid = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=200)
    changed = models.BooleanField(default = False)
    def __unicode__(self):
    return self.name
    class Meta:
        managed = False
        db_table = 'Playlists'

class Stationplaylist(models.Model):
     spid = models.IntegerField(primary_key=True, db_column='spid')
     sid = models.ForeignKey(Station, db_column='sid')
     plid = models.ForeignKey(Playlist, db_column='plid')
     syncronized = models.BooleanField()
     def __unicode__(self):
          return self.plid.name
     class Meta:
         managed = False
         db_table = 'StationsPlaylists'
         unique_together=('sid', 'plid')

我想在我的视图中执行插入操作:

def addPlaylist(request, app_label='webadmin', **kwargs):
    # stuff...
    selected_playlists = request.POST.getlist('selected_playlists[]')
    current_station = request.POST.get('station')
    totalPlaylists = Stationplaylist.objects.filter(sid=current_station).count()
    last_spid = None        
    for playlist in selected_playlists:
        if playlist != 'on':
            if totalPlaylists==0:
                last_spid=1
            elif last_spid == None:
                last_obj = Stationplaylist.objects.order_by('-pk')[0]
                last_spid = last_obj.spid + 1
            else:
                last_spid += 1
            Stationplaylist(last_spid, current_station, playlist, 0).save() # 0-syncronized
            totalPlaylists+=1
    return HttpResponse('OK')

但是当我打电话给这个时,比如站#1,有3个播放列表然后我在另一个上调用它,让它成为第2站,播放列表只是更新。我的意思是,在数据库中,他们的站点字段更新到站#2。

为什么会发生这种情况以及如何解决?

提前致谢

1 个答案:

答案 0 :(得分:0)

您已覆盖自动主键并使其成为纯IntegerField。这不会自动增量,因此每个新实例都会获得相同的默认主键。

除非你有充分的理由,否则你真的不应该定义自己的主键字段。但如果你有充分的理由,你应该使用AutoField而不是IntegerField。