[英]Many to Many Nested Relationship as List in Django Rest Framework
I'm building an API using the Django Rest Framework and I have two models that share a many to many relationship. 我正在使用Django Rest Framework构建API,并且我有两个共享多对多关系的模型。 The models are Contacts and Tasks.
模型是联系人和任务。 A Task can be shared with several Contacts and a Contact can have many Tasks shared with it.
一个任务可以与多个联系人共享,一个联系人可以与之共享多个任务。 I'm also using a manual join table, rather than Django's built-in many-to-many relationship.
我还使用了手动联接表,而不是Django内置的多对多关系。
In the API, I'd like to have the method for retrieving Tasks include a list of Contacts with whom the Task has been shared. 在API中,我希望检索任务的方法包括与任务共享的联系人列表。 I have a way of accomplishing this currently, but it isn't great.
我目前有一种方法可以完成此任务,但这不是很好。 The serialized Task has an attribute
shared_with
, which is a related field that goes through the SharedWithSerializer
class (which is the version of the ContactTaskJoin serializer for this side of the relationship). 序列化的Task具有属性
shared_with
,这是一个通过SharedWithSerializer
类(这是关系的这一方面的ContactTaskJoin序列化程序的版本)的相关字段。 So the output is quite clunky. 因此输出非常笨拙。 The
SharedWithSerializer
has just one attribute— contact
—which references the ContactSerializer
class. SharedWithSerializer
仅具有一个属性contact
—引用ContactSerializer
类。 An example Task returned by the API: API返回的示例任务:
{
'id': 100,
'shared_with': [
{
'contact': {
'id': 1,
'name': 'Alice'
}
},
{
'contact': {
'id': 2,
'name': 'Bob'
}
}
]
}
What I would like is to just have a plain list of the Contacts with whom the Task was shared. 我只想简单地列出与任务共享的联系人。 Something like:
就像是:
{
'id': 100,
'shared_with': [
{
'id': 1,
'name': 'Alice'
},
{
'id': 2,
'name': 'Bob'
},
]
}
Any suggestions would be much appreciated. 任何建议将不胜感激。
You could override to_representation
on the SharedWithSerializer
to flatten the contact fields one level up 您可以覆盖
to_representation
上的SharedWithSerializer
以将联系人字段展平到上一层
For example 例如
class SharedWithSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
representation = super().to_representation(obj)
shared_with = representation.pop('shared_with')
representation['shared_with'] = [entry['contact'] for entry in shared_with]
return representation
I hope this helps resolve you issue. 希望这有助于解决您的问题。 If you could also post your models.py and serializers.py I can provide a more tailored answer, if necessary.
如果您还可以发布您的models.py和serializers.py,则如有必要,我可以提供更适合您的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.