2013-04-30 11 views
2

我正在構建一個Web應用程序,該應用程序允許用戶擁有一個照片庫,充滿照片對象,可以將照片對象放入相冊中。他們可以做到以下幾點:Django:ManyToMany能夠訂購和添加/刪除關係嗎?

  • 添加照片到相冊
  • 從相冊
  • 更改照片的相冊
  • 內的順序放入多個相冊
  • 同一張照片中刪除照片
  • 將照片入冊多次

我本來以爲寫的車型像這樣(簡化):

def Photo(models.Model): 
    user = models.ForeignKey(User) 
    img_file = models.ImageField(upload_to = img_get_file_path) 
    upload_date = models.DateTimeField(auto_now_add = True) 


def Album(models.Model): 
    title = models.CharField(max_length = 50, required = False) 
    cover_img = models.ForeignKey(Photo) 
    album_contents = models.ManyToMany(Photo) 

# a user's "photo library" isn't defined in a model, but 
# rather by running the query: 
# Photo.objects.filter(user = request.user).order_by('upload_date') 

這個簡單的方法會工作進展順利,但用戶無法更改他們的相冊中的照片順序(ManyToMany relationships是不排序)。我搜索了一個解決方案,這一點,每個人都指着使用intermediate models,使用through聲明:

中間模型的方法將在訂購照片工作該專輯,但而不是從相冊中刪除照片。 Intermediate models不支持.add(),.create(),.remove()或轉讓。他們只支持.clear()方法,這將清除整個相冊。我需要用戶能夠一次從相冊中刪除一張照片,同時仍然可以在相冊中排列照片。

我該如何做到這一點?

回答

4

你不應該讓django刪除添加,創建,刪除阻止你做任何事情的事實。

僅僅因爲它「僅」支持.clear()方法,並不意味着您不能編寫普通的Python代碼來替換該功能。

中間模型方法可用於訂購相冊中的照片,但不適用於從相冊中刪除照片。中間模型不支持.add(),.create(),.remove()或賦值。他們只支持.clear()方法,這會清除整個相冊。我需要用戶能夠一次從相冊中刪除一張照片,同時仍然可以在相冊中排列照片。

我沒有看到什麼阻止你從一個關係而不是所有的關係中刪除。

只需找到M2M中間表的實例並刪除該行即可。這是一個正常的Django模型。

# say you have a photo that the user wants to remove from album. 
album = Album.objects.latest('id') 
photo = Photo.objects.album_contents.latest('id') 

# to remove that m2m relationship... 
# delete the through table row which matches said relationship 
MyThroughTable.objects.filter(album=album, photo=photo).delete()