简体   繁体   中英

Manage Many-to-many relationships in Django

I need a many-to-many Django relationship; something like this:

  • I have User model
  • I have Locations model

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.

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. Then you can query the UserLocation table to see if any instances of that location remain for other users. If not, delete the location.

For example: Billy and Sally are users. Billy adds New York, which is a new location. You create the Location entry and then the UserLocation entry. Now Sally adds New York. New York is already there so you only need to create UserLocation for her.

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. 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.

Perhaps you'd do this checking and deleting of location by overriding the UserLocation delete() method?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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