0

TastyPie在这里展示了如何列出ContentTypesGenericForeignKeys。我有这个工作,但是你如何做一个POST来创建一个具有通用外键的资源?

这是我的资源:我现在想创建一个新的活动,同时创建一个新的 SingleVoucherReward 或 MultiVoucherReward,然后链接它。如何在 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
4

0 回答 0