我有下面列出的三种型号。当我序列化媒体对象时,列出的所有者就像他们应该的那样。槽表保持is_accepted
值,我想要的是媒体序列化器只列出拥有其媒体的所有者。关于如何实现这一点的任何想法?
型号:
class Media(models.Model):
genre = models.ForeignKey(Genre, blank=True, null=True, db_index=True)
owners = models.ManyToManyField(User, through='Usermedia', related_name='owners')
title = models.CharField(max_length=45, blank=True)
created = models.DateTimeField(auto_now_add=True)
class Usermedia(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='usermedia')
media = models.ForeignKey(Media, on_delete=models.CASCADE, related_name='ownership')
is_active = models.BooleanField(default=0)
is_accepted = models.BooleanField(default=1)
class User(AbstractBaseUser, PermissionsMixin):
email=models.CharField(unique=True, max_length=255)
串行
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
validators=[validators.UniqueValidator(queryset=User.objects.all())]
)
class MediaSerializer(serializers.ModelSerializer):
owners = UserSerializer(many=True, required=False)
created = serializers.DateTimeField(read_only=True)
genre = serializers.SlugRelatedField(required=True, slug_field='name', queryset=Genre.objects.all())
感谢您抽出宝贵时间来看看这个
答案 0 :(得分:0)
我最终使用array[i]
。
我的序列化程序现在看起来像这样:
SerializerMethodField
一个提示是确保在将结果传递给序列化程序之前预取相关字段,否则序列化程序将对它解析的每个实例进行数据库查找。