以下是简化的模型定义
class Resource(models.Model):
name = models.CharField(max_length=100, unique=True)
class Location(models.Model):
name = models.CharField(max_length=100, unique=True)
resources = models.ManyToManyField(Resource)
我想知道一种类型的Resource
,在每一种Location
上的存在.所以我想要的json数据如下所示
[
{
"id": 1,
"name": "loaction_A",
"resource": true
},
{
"id": 2
"name": "location_B",
"resource": false
},
...
]
我try 了跟踪视图函数,但显然得到了错误的结果.
def resource_view(request, res_id):
res = get_object_or_404(Resource, pk=res_id)
locations = Location.objects.values('id', 'name')\
.annotate(resource=Q(resources=res))
return JsonResponce({'locations': list(locations)})
我知道我需要类似下面这样的东西(在SQL中)
select
app_location.*,
1 in (
select resource_id
from app_location_resources
where location_id = app_location.id
) as resource
from app_location
我应该如何构造查询集?