首页 > 解决方案 > Django rest api 过滤错误信息:django.core.exceptions.FieldError: Related Field got invalid lookup

问题描述

我正在尝试使用名称查询我的数据库,其中包含将使用此查询MainName进行过滤:Profile

Profile.objects.all().filter(simmatch__mainname__mainname=name.lower())

但我收到此错误消息:

django.core.exceptions.FieldError:相关字段查找无效:​​主名称

有人可以告诉我我做错了什么吗?我对 Django 很陌生。谢谢!

我的模型:

class Profile(models.Model):
    ID = models.IntegerField(unique=True, primary_key=True)
    name = models.CharField(max_length=200)
    hasArticle       = models.CharField(max_length=3)
    gender_guessed   = models.CharField(max_length=5)
    age              = models.CharField(max_length=5)
    profile = models.TextField()

    def __str__(self):
        return "{}".format(self.name)

class MainName(models.Model):
    ID = models.IntegerField(unique=True, primary_key=True)
    mainName = models.CharField(  max_length=100) 

    def __str__(self):
        return "{}".format(self.mainName)


class SimMatch(models.Model):
    profile = models.ForeignKey(Profile,to_field="ID", db_column="profile_ID",on_delete=models.CASCADE,)
    mainName  = models.ForeignKey(MainName, to_field="ID", db_column="ID",on_delete=models.CASCADE,)

    def __str__(self):
        return "{}-{}".format(self.mainName,self.profile)

我的查询:

Profile.objects.all().filter(simmatch__mainname__mainname="My Name")

标签: djangodjango-modelsdjango-rest-framework

解决方案


将您的查询更改为:

Profile.objects.all().filter(simmatch__mainName__mainName="My Name")

你不应该使用小写的显式字段。


推荐阅读