简体   繁体   中英

How to join tables by list of ids in Django ORM

I have two tables - Players and Buildings. For example:

class Players(models.Model):
    username = models.CharField(max_length=500)
    buildings = models.CharField(validators=[int_list_validator], default=list, max_length=100)

class Buildings(models.Model):
    building_name = models.CharField(max_length=500)

Player can have a lot of buildings, there are in the Player.buildings field as list of ids. I need to write a query to get building information for the player. In Postgres SQL, I got that query:

SELECT *
FROM players p
LEFT JOIN buildings b on b.id=ANY(buildings) where p.id = %s;

But how I can write that SQL query, using Python and Django ORM?

You should use singular names for your models.

class Player(models.Model):
    username = models.CharField(max_length=500)
    buildings = models.ManyToManyField(Building)

class Building(models.Model):
    building_name = models.CharField(max_length=500)

Now when you want to access the set of buildings for your player you can do the following:

Player.objects.get("pk of player").buildings.all()

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