我有下一个型号:
class Product(models.Model):
name = models.CharField(max_length=500, blank=False, null=False)
class ProdcutsAccess(models.Model):
user = models.ForeignKey(User)
product = models.ForeignKey(Product,related_name='hidden_products')
我想要序列化Product类,并在那里有' hidden_users'看起来像是:
hidden_users:[mark,joe,sam]
即。用户名列表
我的serailizers看起来像:
class ProductSerializer(serializers.ModelSerializer):
hidden_users = serializers.SlugRelatedField(many=True, slug_field='user', read_only=False, source='hidden_products',queryset=User.objects.all())
但我收到了错误
不是JSON可序列化的
如何赢得它?
答案 0 :(得分:0)
我可以建议使用SerializerMethodField的解决方法:
class ProductSerializer(serializers.ModelSerializer):
hidden_users = serializers.SerializerMethodField()
def get_hidden_users(self, product):
hidden_users = product.hidden_products.values_list('user', flat=True)
return [user.name for user in hidden_users]
class Meta:
model = Product