访问QuerySet中的Django M2M值,而无需循环
我通过AJAX收到一些数据,使我可以对具有M2M关系的模型进行一些过滤(例如模型)。我得到一个QuerySet,说“内容”,然后我需要使用JSON发送回。这是代码的简化行:
content = Models.objects.all()
content = content.values
return JsonResponse({"data":list(content)})
它运行良好,但是项目更改了,我现在需要在每个QuerySet结果实例上包含某些M2M相关模型的值,问题是content = model.object.objects.abresss.abresss.abects.aberss.acks.all(all)(all)。 )当然不会给我这些价值观,而没有一些循环,所以我被卡住了。我记得在DRF中使用了在这里完成工作的深度选项,但不幸的是,由于项目过于先进和实时,我现在无法做到这一点。有什么方法可以直接在QuerySet中添加M2M相关值的结果? 非常感谢
此处添加简化模型:
class Content(models.Model):
uuid = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False)
pathology = models.ManyToManyField(Pathology, null=True, blank=True)
organs = models.ManyToManyField(Organ, null=True, blank=True)
title = models.CharField(verbose_name="Titre",
max_length=255, null=True, blank=False)
document = models.ForeignKey(
'wagtaildocs.Document',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="+",
)
description = RichTextField(null=True, blank=True)
class Pathology(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.title
class Organ(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.title
I receive some data through Ajax that allows me to do some filtering on a model that has some m2m relations (say Model). I get a queryset, say "content" that I then need to send back using json. Here are simplified lines of code:
content = Models.objects.all()
content = content.values
return JsonResponse({"data":list(content)})
It was working fine but the project changed and I now need to include the values of some of the m2m related models attached to Model to each queryset result instances, problem is that content=Model.objects.all() will of course not give me these values without some looping so I am stuck. I remember using a depth option in DRF that would have done the job here but unfortunately I cannot do this now as the project is too advanced and live. Any way to add directly in the queryset the results of the m2m related values ?
Many many thanks
Adding simplified models here :
class Content(models.Model):
uuid = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False)
pathology = models.ManyToManyField(Pathology, null=True, blank=True)
organs = models.ManyToManyField(Organ, null=True, blank=True)
title = models.CharField(verbose_name="Titre",
max_length=255, null=True, blank=False)
document = models.ForeignKey(
'wagtaildocs.Document',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="+",
)
description = RichTextField(null=True, blank=True)
class Pathology(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.title
class Organ(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.title
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请不要使用
.values(…)
  [django-antipatterns] ,这些侵蚀了模型层中的逻辑。此外,您不能使用.values(…)
双向:您只能将记录转换为字典,而不是将词典变成模型对象。在 postgresql 中,您可以使用
arrayagg
  [django-doc] ,这是一个唯一适用于postgresql,此外,这可能也不是理想的,因为它再次使序列化过程变得笨拙。您可以将其用作:使用但是,使用当前视图仍然可以。您可以安装此框架并使用以下方式定义一个序列化器:
然后在视图中可以使用:
Please don't use
.values(…)
[Django-antipatterns], these erode the logic in the model layer. Furthere you can not use.values(…)
bidirectionally: you can only convert records into dictionaries, not deserialize dictionaries into model objects.In PostgreSQL you can make use of
ArrayAgg
[Django-doc], this is an aggregate that only works for PostgreSQL, and furthermore it is probably not ideal either, since again it makes adapting the serialization process cumbersome. You can use this as:Using The Django REST framework is however still possible with the current view. You can install this framework and define a serializer with:
Then in the view you can work with:
Willem使用DRF的解决方案是正确的,但仅返回相关字段的ID。我想有一种方法可以更改此问题并获得另一个字段,但我找到了另一种方法,而无需覆盖:
其余解决方案已亮起。
还没有尝试过PGSQL
Willem's solution using DRF is correct yet returns only the ID of the related fields. I suppose there is a way to change this and get another field yet instead I found another way with no override needed:
Rest of the solution was spot on.
Didn't try the prod PGSQL yet