gpt4 book ai didi

python - 如何序列化类对象特定字段的数组(getStream)

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:20 26 4
gpt4 key购买 nike

我正在尝试将 EnrichedActivity 数据推送到 FeedSerializer。我正在使用 getStream

获取 Feed 数据
class FeedAPIView(APIView):
def get(self, request, format=None):
feeds = feed_manager.get_news_feeds(request.user.id)
# get the newsfeed for user.
activities = feeds.get('timeline').get()['results']
activities = enricher.enrich_activities(activities)
# I want to serialize only Outfit instances(object) from the activities.
filtered_set = FeedSerializer(activities.getObject.convertToQueryset)
json_output = { "feed" : filtered_list }
return Response(json_output, status=status.HTTP_200_OK)

这是来自事件的数组数据

[
EnrichedActivity(
activity_data={
'target': None, 'verb': 'outfit', 'actor': <User: georgiamason522>,
'to': [], 'foreign_id': 'outfit.Outfit:23',
'id': 'x7x7bxxxxxxxxxxx3xbxx',
'object': <Outfit: georgiamason522 23>, // Data
'time': datetime.datetime(2017, 12, 14, 1, 36, 6, 833617), 'origin': 'user:17'},
not_enriched_data={}),
EnrichedActivity(..., 'object': <Outfit: georgiamason522 22>,
]

我想从上面的数组中获取这个查询集,

filtered_set = ???
print(filtered_set)
<QuerySet [<Outfit: georgiamason522 23>, <Outfit: georgiamason522 22>]>

将查询集放入 FeedSerializer。

FeedSerializer(filtered_set, many=True, context={'request': self.context['request']}).data

我的问题是...

  1. EnrichedActivity 数据看起来像类对象。我们如何仅提取 activity_data > object

  2. 将提取的对象数据转换为查询集

这是伪代码,可能是正确的。

# This is Pseudo Code in my mind! This is not correct or can be not even close
filtered_set = [activity.activity_data.object].getQueryset for activity in activities

如果有任何不清楚或需要更多信息,请在下面发表评论。

更新

class FeedSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField()
...
is_owner = serializers.SerializerMethodField()

class Meta:
model = Outfit # I want to serialize Outfit Model instance
# from feed in enriched list

...

服装模型//你可以把它想象成普通的帖子

class Outfit(models.Model, Activity):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
...

@property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type

@property
def activity_object_attr(self):
return self

@property
def activity_notify(self):
targets = [feed_manager.get_news_feeds(self.user.id)['timeline']]

最佳答案

这是我的解决方案。感谢...@DwightGunning

    feed = []
for activity in activities:
outfit_instance = activity.__dict__.get('activity_data').get('object')
data = FeedSerializer(
outfit_instance,
context={'request': request}).data
feed.append(data)

json_output = { "feed" : feed }

关于python - 如何序列化类对象特定字段的数组(getStream),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47804843/

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