我正在学习Django Rest Framework的序列化。但是,当我定义了序列化程序时,出现了“ XXXSerializer未定义”错误。
因此,在我的项目中,我有2个模型: CustomUser 和 Clique 。关系应该是:
我的models.py:
class CustomUser(AbstractUser):
created = models.DateTimeField(auto_now_add=True)
job = models.CharField(max_length=100, blank=False)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Meta:
ordering = ('created', )
class Clique(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=100, blank=False)
founder = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
members = models.ManyToManyField(CustomUser)
def __str__(self):
return self.name
class Meta:
ordering = ('created', )
我的serializers.py:
class CustomUserSerializer(serializers.HyperlinkedModelSerializer):
# this line causes the error. I know that CliqueSerializer is defined below.
owned_cliques = CliqueSerializer(many=True, read_only=True)
class Meta:
model = CustomUser
fields = ('url', 'id','username', 'first_name', 'last_name', 'job','owned_cliques', 'clique_set')
class CliqueSerializer(serializers.HyperlinkedModelSerializer):
members = CustomUserSerializer(read_only=True, many=True)
class Meta:
model = Clique
fields= ('id', 'name', 'members',)
结果是,出现“ NameError:未定义名称'CliqueSerializer'” 错误。似乎存在依赖性问题。我该如何解决?