2014-03-19 53 views
1

我的模型如下:Django管理不更新,而不是插入

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。

爲什麼會發生這種情況以及如何解決?

在此先感謝

回答

0

你覆蓋了自動主鍵,並使它成爲純IntegerField。這不會自動增加,所以每個新實例都獲得相同的默認主鍵。

除非有很好的理由,否則你不應該定義自己的主鍵字段。但是如果你確實有這個好理由,你應該使用AutoField而不是IntegerField。

+0

我正在使用last_spid來模擬auto_increment。 感謝您的鏈接。 –

+0

Yuck,我只注意到了代碼。請不要這樣做:你受到各種可怕的競賽條件的影響。 –

+0

好吧,我將該字段更改爲AutoField,當我做 p = Playlistsong(current_playlist,song,totalSongs + 1) p.save() 服務器返回'內部錯誤'。 會導致什麼? –

相關問題