gpt4 book ai didi

python - Django-Tastypie : Omit one specific object to be serialized in ManyToMany

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:28 24 4
gpt4 key购买 nike

我有一个简单的聊天应用程序。这是我的模型。

class Thread(models.Model):
participants = models.ManyToManyField(User, related_name= 'threads_partof')
last_message_time = models.DateTimeField(null=True, blank=True)

class Message(models.Model):
message = models.CharField(max_length=500)
sender = models.ForeignKey(User)
thread = models.ForeignKey(Thread, related_name = 'thread_to_message')
datetime = models.DateTimeField(auto_now_add=True)

def update_last_message_datetime(sender, instance, created, **kwargs):
'''
Update Thread's last_message field when
a new message is sent.
'''
if not created:
return

Thread.objects.filter(id=instance.thread.id).update(last_message_time=instance.datetime)
post_save.connect(update_last_message_datetime, sender=Message)

我使用 Django-Tastypie 作为我的 API。这是我的应用程序当前工作方式的示例,如果史蒂夫想要向比尔发送消息,则会创建一个新的“消息”对象,其中史蒂夫是发送者。当创建消息对象时,它也会创建一个“Thread”对象。在这个帖子中,参与者是 Steve 和 Bill。

我当前有一个 ThreadPreview 资源。

class ThreadPreview(ModelResource):
participants = fields.ManyToManyField(BasicFoodieActivityResource, 'participants', full=True)
class Meta:
queryset = Thread.objects.all()
resource_name = 'thread-preview'
fields = ['id', 'participants', 'last_message_time']
authorization = Authorization()
authentication = BasicAuthentication()
serializer = Serializer(formats=['json'])
include_resource_uri = False
always_return_data = True

def dehydrate(self, bundle):
bundle.data['last_message'] = bundle.obj.thread_to_message.latest('datetime').message
return bundle

def get_object_list(self, request):
return super(ThreadPreview, self).get_object_list(request).filter(participants = request.user).order_by('-last_message_time')

当我对此资源执行 HTTP GET 请求时,我得到的结果是:

{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [{
"id": "12",
"last_message": "Hey, Bill, you're stealing from us!",
"last_message_time": "2013-11-07T19:27:52",
"participants": [{
"user": {
"first_name": "Steve",
"id": "28",
"last_name": "Jobs",
"username": "steve"
},
"userPic": "http://apple.com/stevejobs.jpg"
}, {
"user": {
"first_name": "Bill",
"id": "6",
"last_name": "Gates",
"username": "bill"
},
"userPic": "http://microsoft.com/billgates.jpg"
}],
}]
}

当数据返回时,我不想包括用户 Steve,因为他是 request.user。每当 request.user 访问此数据时,我都希望他们的用户数据不被序列化,因为我已经知道他们是谁。例如,这就是我想要的:

{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [{
"id": "12",
"last_message": "Hey, Bill, you're stealing from us!",
"last_message_time": "2013-11-07T19:27:52",
"participants": [{
"user": {
"first_name": "Bill",
"id": "6",
"last_name": "Gates",
"username": "bill"
},
"userPic": "http://microsoft.com/billgates.jpg"
}],
}]
}

我该如何执行此操作,以便始终忽略 request.user 的数据?

最佳答案

此问题的案例(过滤相关资源)

您可以在 ThreadPreview 上使用 deHydrate_participants 钩子(Hook) ( see docs on dehydration ) 来过滤参与者:

class ThreadPreview(ModelResource):

...

def dehydrate_participants(self, bundle):
if not hasattr(bundle.request, 'user'):
return bundle.data['participants']

new_participants = []
for p in bundle.data['participants']:
if p['user']['id'] != bundle.request.user.pk:
new_participants.append(p)

return new_participants

...

注意:我对p['user']['id'] !=bundle.request.user.pk的理解可能是错误的。 p['user']['id'] 可能已经是字符串。

仅当资源被序列化时(而不是当它相关时)

Resource 有一个钩子(Hook)方法 def get_object_list(self, request)它可用于根据 request.user 过滤列表。实现是战略性的

class BasicFoodieActivityResource(ModelResource):

...

def get_object_list(self, request):
qs = super(BasicFoodieActivityResource, self).get_object_list(request)

if request and hasattr(request, 'user'):
qs = qs.exclude(pk = request.user.pk)

return qs

...

关于python - Django-Tastypie : Omit one specific object to be serialized in ManyToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19848110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com