问题描述
我正在尝试对两个表进行联接-希望从ReleasesAll和AudioLinks返回所有数据。
错误
位于/ api / release / 0的FieldError
select_related中指定的字段名称无效:“ audio_links”。 选择是:(无)
models.py
class ReleasesAll(models.Model):
id = models.IntegerField(primary_key=True)
artist = models.CharField(max_length=255)
all_artists = models.CharField(max_length=200)
remixers = models.TextField(blank=True, null=True)
format = models.CharField(max_length=80)
title = models.CharField(max_length=255)
label = models.CharField(max_length=255)
label_no_country = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'releases_all'
class AudioLinks(models.Model):
release = models.ForeignKey('ReleasesAll', models.DO_NOTHING, db_column='release_id')
track_number = models.IntegerField()
track_name = models.CharField(max_length=500)
url = models.CharField(max_length=500)
m3u_link = models.TextField()
type = models.CharField(max_length=50, blank=True, null=True)
class Meta:
managed = False
db_table = 'audio_links'
views.py
class ListReleaseDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = ReleasesAll.objects.all()
serializer_class = ReleasesSerializer
def get(self, request, *args, **kwargs):
try:
a_release = self.queryset.select_related('audio_links__release_id').get(pk=kwargs['release_id'])
return Response(ReleasesSerializer(a_release).data)
except ReleasesAll.DoesNotExist:
return Response(
data = {
"message": "{} does not exist".format(kwargs["release_id"])
},
status=status.HTTP_404_NOT_FOUND
如果删除select_related
则查询有效
1楼
您应该将prefetch_related
用于多个关系。
另外的说法prefetch_related
应related_name
值,或者audiolinks_set
你的情况:
a_release = self.queryset.prefetch_related('audiolinks_set').get(pk=kwargs['release_id'])
参见 :
select_related仅限于单值关系-外键和一对一关系。