在TastyPi中使用GenericForeignKey创建一个资源帖子

2024-04-18 10:07:23 发布

您现在位置:Python中文网/ 问答频道 /正文

tastypice展示了here如何列出内容类型通用外键。我有这个工作,但是你怎么做一个帖子来创建一个具有通用外键的资源?你知道吗

这是我的资源:我现在想创建一个新的活动,同时创建一个新的单凭证奖励或多凭证奖励,然后链接它。如何在TastyPie中实现这一点?你知道吗

class CampaignCreateResource(ModelResource):
    """
    API Facet.
    """
    user = fields.ToOneField(UserResource, 'user',  full=True)

    participant_reward = GenericForeignKeyField({
        SingleVoucherReward: SingleVoucherResource,
        MultiVoucherReward: MultiVoucherResource,
    }, 'participant_reward')

    class Meta:
        queryset = Campaign.objects.all()
        resource_name = 'campaign'
        allowed_methods = ['post', 'get']
        authentication = APIAuthentication().get_authentication()
        authorization = UserObjectsOnlyAuthorization()
        validation = FormValidation(form_class=CampaignForm)
        excludes = ['id', 'participant_reward_object_id']

    def hydrate(self, bundle, request=None):
        """
        Tastypie uses a 'hydrate' cycle to take serializated data from the client
        and turn it into something the data model can use.
        """
        bundle.obj.user = get_user_model().objects.get(pk=bundle.request.user.id)
        return bundle

Tags: iddatagetauthenticationobjectsrequest资源外键