簡體   English   中英

管理Django中的多對多關系

[英]Manage Many-to-many relationships in Django

我需要一個多對多的Django關系; 這樣的事情:

  • 我有用戶模型
  • 我有Locations模型

用戶可以添加更多位置。 我需要避免在Locations中重復這樣:如果更多用戶添加相同的位置(即紐約),我將在Locations Model中有一個位置“NewYork”。

當用戶刪除位置時,如果沒有其他用戶鏈接到該位置,則也會刪除位置表中的相應元素。

我該如何處理這種情況?

所以我們說:

class Location(models.Model):
    name = models.CharField(unique=True)

class User(models.Model):
    locations = models.ManyToManyField(Location, through='UserLocation')
    name = models.CharField(unique=True)

class UserLocation(models.Model):
    user = models.ForeignKey(User)
    location = models.ForeignKey(Location)

您可能不需要顯式定義中間表,但我們在此處使用它來表明它。 這是一個簡單的多對多設置。

當用戶刪除位置時,您將刪除相應的UserLocation條目。 然后,您可以查詢UserLocation表以查看該位置的任何實例是否仍為其他用戶保留。 如果沒有,請刪除該位置。

例如:Billy和Sally是用戶。 比利增加紐約,這是一個新的位置。 您創建Location條目,然后創建UserLocation條目。 現在莎莉補充說紐約。 紐約已經存在,所以你只需要為她創建UserLocation。

后來,莎莉刪除了紐約。 首先刪除UserLocation條目,然后檢查並查看Billy還有一個紐約條目,因此您可以單獨保留位置。 現在比利刪除了紐約。 刪除他的UserLocation條目后,您會看到紐約不再有實例,因此您可以刪除該位置。

也許您通過重寫UserLocation delete()方法來檢查和刪除位置?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM