当前位置: 代码迷 >> python >> 尝试加入并获取在select_related:'audio_links'中给定的无效字段名称。 选择是:(无)
  详细解决方案

尝试加入并获取在select_related:'audio_links'中给定的无效字段名称。 选择是:(无)

热度:56   发布时间:2023-06-19 09:14:39.0

我正在尝试对两个表进行联接-希望从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则查询有效

您应该将prefetch_related用于多个关系。 另外的说法prefetch_relatedrelated_name值,或者audiolinks_set你的情况:

a_release = self.queryset.prefetch_related('audiolinks_set').get(pk=kwargs['release_id'])

参见 :

select_related仅限于单值关系-外键和一对一关系。