简体   繁体   English

管理Django中的多对多关系

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

I need a many-to-many Django relationship; 我需要一个多对多的Django关系; something like this: 这样的事情:

  • I have User model 我有用户模型
  • I have Locations model 我有Locations模型

Users can add more Locations. 用户可以添加更多位置。 I need to avoid duplicates in Locations so: If more Users add same location (ie New York) I would have a single Location "NewYork" in Locations Model. 我需要避免在Locations中重复这样:如果更多用户添加相同的位置(即纽约),我将在Locations Model中有一个位置“NewYork”。

When a user deletes a Location, the corresponding element in the Locations table will also be deleted if no other users are linked to that location. 当用户删除位置时,如果没有其他用户链接到该位置,则也会删除位置表中的相应元素。

How should I handle this scenario? 我该如何处理这种情况?

So let's say: 所以我们说:

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)

You may not need to explicitly define an intermediate table but let's use it here to make it clear. 您可能不需要显式定义中间表,但我们在此处使用它来表明它。 This is a simple many to many setup. 这是一个简单的多对多设置。

When a user deletes a location, you're deleting the corresponding UserLocation entry. 当用户删除位置时,您将删除相应的UserLocation条目。 Then you can query the UserLocation table to see if any instances of that location remain for other users. 然后,您可以查询UserLocation表以查看该位置的任何实例是否仍为其他用户保留。 If not, delete the location. 如果没有,请删除该位置。

For example: Billy and Sally are users. 例如:Billy和Sally是用户。 Billy adds New York, which is a new location. 比利增加纽约,这是一个新的位置。 You create the Location entry and then the UserLocation entry. 您创建Location条目,然后创建UserLocation条目。 Now Sally adds New York. 现在莎莉补充说纽约。 New York is already there so you only need to create UserLocation for her. 纽约已经存在,所以你只需要为她创建UserLocation。

Later, Sally deletes New York. 后来,莎莉删除了纽约。 You remove the UserLocation entry first, and then check and see there is still a New York entry for Billy, so you leave the Location alone. 首先删除UserLocation条目,然后检查并查看Billy还有一个纽约条目,因此您可以单独保留位置。 Now Billy deletes New York. 现在比利删除了纽约。 After deleting his UserLocation entry you see there are no more instances of New York so you can delete the location. 删除他的UserLocation条目后,您会看到纽约不再有实例,因此您可以删除该位置。

Perhaps you'd do this checking and deleting of location by overriding the UserLocation delete() method? 也许您通过重写UserLocation delete()方法来检查和删除位置?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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