【发布时间】:2021-11-16 00:57:27
【问题描述】:
这是我的序列化器
class SparkleTemplateSerializer(serializers.ModelSerializer):
notifications = NotificationTemplateSerializer(source='notificationtemplate_set', many=True)
rules = RuleTemplateSerializer(source='ruletemplate_set', many=True)
class Meta:
model = SparkleTemplate
fields = ['id', 'name', 'description', 'enabled', 'run_schedule', 'notifications', 'rules']
我需要显示和隐藏“通知”字段,如您所见,这是外键,但如果某些变量是真或假,则需要发生这种情况。
这就是我尝试的方法,通过将下面的代码添加到序列化程序中,但我猜它不起作用,因为 Meta 中的 fields 属性
def to_representation(self, obj):
show = NotificationTemplate._meta.get_field('show')
rep = super(SparkleTemplateSerializer, self).to_representation(obj)
if show is False:
rep.pop('notifications', None)
return rep
我还尝试排除“通知”并创建另一个序列化程序,但这不起作用,因为“通知”必须存在,所以我遇到了错误。谢谢
编辑 1: SparklesTemplate 模型
company = models.ForeignKey(
Company, on_delete=models.DO_NOTHING, blank=False, default=1)
name = models.CharField(max_length=64, blank=False)
description = models.CharField(max_length=256, blank=False, default="")
enabled = models.BooleanField(default=False, blank=False)
visible = models.BooleanField(default=True, blank=False)
# sparkle must determine just how often it should run.
# a cron string is the most flexible way to determine the schedule
run_schedule = models.CharField(max_length=128, blank=False, default="*/15 * * * *",
help_text="The cron formatted schedule that the notifications will trigger on.")
# this will be appended to the end of the get visits query
query_extra_arguments = models.CharField(max_length=256,
blank=True,
help_text="Extra arguments that will be added to the get visits query.")
branch_owner = models.ForeignKey(Branch, on_delete=models.DO_NOTHING, blank=True, default=None, null=True, help_text="Dictates the visibility of the users.")
NotificationTemplate 模型:
sparkle = models.ForeignKey(
SparkleTemplate, on_delete=models.CASCADE, blank=False)
enabled = models.BooleanField(default=True)
show = models.BooleanField(default=True)
class_name = models.ForeignKey(
NotificationClass, on_delete=models.CASCADE, blank=False)
class_args = models.TextField(max_length=16384, default="{}", blank=False)
另外,我在我的帖子中混淆了外键的方向,是相反的。
编辑 2 查看.py
class SparkleTemplateView(ListAPIView):
serializer_class = SparkleTemplateSerializer
def get_queryset(self):
user = self.request.user
return SparkleTemplate.objects.filter(branch_owner=user.branch)
【问题讨论】:
-
你能分享你的模型吗?
-
@NielGodfreyPonciano 我做到了。另外,我现在不确定“pop”是否不起作用,因为“通知”最初不在 SparkleTemplate 模型中
-
如果任何个实例
show字段设置为False,您想从表示中删除NotificationTemplate实例吗?还是您只想显示show为True的NotificationTemplate实例? -
@NielGodfreyPonciano show 默认为 true,因此 NotifTemp 在为 true 时会显示,在通过管理面板设置为 false 时应隐藏。不,我只想隐藏显示字段设置为 false 的 NotifTemplates,但我可以使用过滤器修复它。
-
你能展示一下你的观点吗?您可以使用与视图相关的预取并为
NotificationTemplate提供查询集,它将仅获取show为True的对象。
标签: python django django-rest-framework