Django查询多对多关系

时间:2015-08-04 05:24:01

标签: django orm many-to-many

我有以下模特。

class user(models.Model):
    location = models.ManyToManyField(Locations, blank=True, null=True)

class Locations(models.Model):
    location_id = models.AutoField(primary_key=True, verbose_name='location Id')
    location_name = models.CharField(max_length=512, unique=True, null=True, blank=True, verbose_name='location Name')

我想获得特定用户的所有位置。我写了这个查询

location_list = user.location.through.objects.values('locations_id', 'locations,').filter(user_id=user_id)
    pprint.pprint(location_list)

它正在给出这个结果; [<user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>, <user_location: user_location object>]

1 个答案:

答案 0 :(得分:1)

以下代码可为您提供特定用户的位置信息。

location_list = user.location.all()

然后在你的模板中你必须迭代对象,这样就会影响

    {% for locations in locations_list %}
       {{ locations }}
    {% endfor %}