我有:
# models
class Building(models.Model):
...
class Flat(models.Model):
building = models.ForeignKey(Building)
class Profile(models.Model):
flats = models.ManyToManyField(Flat)
# logic
building = Building.objects.create()
flat_1 = Flat.objects.create(building=building)
flat_2 = Flat.objects.create(building=building)
profile = Profile.objects.create()
profile.flats.add(flat_1)
profile.flats.add(flat_2)
profiles = Profile.objects.filter(flats__building=building)
我获得了profiles
2 个相同的个人资料。我如何用不同的方式注释它们中的每一个flat
:profiles.first().flat == flat_1
和profiles.last().flat == flat_2
?
也许Subquery()
但是如何?
UPD我在一些 DRF 列表视图中需要这个。JSON 中的输出必须类似于:
[
{
"profile_id": 1,
"flat_id": 2
},
{
"profile_id": 1,
"flat_id": 3
}
]