我正在尝试将EnrichedActivity
数据推送到FeedSerializer
。我正在使用getStream
获取供稿数据
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)
这是来自
activities
的数组数据[
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
我的问题是
EnrichedActivity数据似乎是类对象。我们如何仅提取
activity_data
> object
。将提取的
object
数据转换为查询集这是正确的伪代码。
# 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/