【问题标题】:Django Rest Framework custom readonly field dependant on related modelDjango Rest Framework 自定义只读字段依赖于相关模型
【发布时间】:2021-11-18 14:17:32
【问题描述】:

假设 models.py 像:

class User(AbstractUser):
    pass

class Notification(models.Model):
    value = models.CharField(max_length=255)

class NotificationUserLink(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    notification = models.ForeignKey(Notification, on_delete=models.CASCADE)
    active = models.BooleanField(default=True)

规范化而不是仅仅在 Notification 本身上有一个用户字段的重点是,当我想向数百人发送相同的 Notification 时,我只需要 1 个 Notification 对象。假设我在views.py 中也有一个端点,如下所示,用户可以在其中看到他们的所有通知,并且只能看到他们的通知,这是通过过滤查询集来实现的。

class NotificationViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.NotificationSerializer
    model = Notification
    lookup_field='pk'
    def get_queryset(self):
        user = self.request.user
        return Notification.objects.filter(notificationuserlink__user=user)

现在 NotificationUserLink 模型上的“用户”和“通知”对形成了一个候选键(它们一起是唯一的。目前只是通过业务逻辑,但我会在某个时候将实际约束添加到数据库中)。

因此,给定请求中的用户,每个通知(在过滤的查询集中)将有 1 个且只有 1 个 NotificationUserLink 到该用户。因此,从用户的角度来看,该通知要么处于活动状态,要么不处于活动状态,具体取决于 NotificationUserLink 上的“活动”字段。

我想要完成的是将该字段(“活动”)包含在通知的序列化中。 IE。如果用户点击此端点,他们应该会看到如下通知:

[
{
    "value": "Bob commented on your post",
    "active": False
},
{...}, ...
]
etc

我认为要实现这一点,我需要覆盖视图上的“列表”方法。但我不知道怎么做。序列化程序在 list 方法中传递了一个查询集,所以我不确定如何将数据注入其中。

序列化器目前看起来像这样:

class NotificationSerializer(serializers.ModelSerializer):
    class Meta:
        model=Notification
        fields=("value",)

【问题讨论】:

    标签: python django django-models django-rest-framework django-queryset


    【解决方案1】:

    你可以在你的查询集中annotate这样的链接状态:

    Notification.objects.filter(
        notificationuserlink__user=user
    ).annotate(
        active=F('notificationuserlink__active')
    )
    

    然后您可以在序列化程序中添加一个只读字段active 字段:

    class NotificationSerializer(serializers.ModelSerializer):
        active = serializers.BooleanField(read_only=True)
        class Meta:
            model = Notification
            fields = ("active", "value",)
    

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 2015-09-25
      • 2013-01-12
      相关资源
      最近更新 更多