【问题标题】:Django Tastypie: post value in multiple models to a single Tastypie ResourceDjango Tastypie:将多个模型中的值发布到单个 Tastypie 资源
【发布时间】:2016-06-24 17:23:36
【问题描述】:

第一个模型:

class Profile(models.Model):

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(
                r'^[\w.@+-]+$',
                _('Enter a valid username. This value may contain only '
                  'letters, numbers ' 'and @/./+/-/_ characters.')
            ),
        ],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
   password = models.CharField(max_length=12, default='123456')
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

第二个模型:

class UserEbiz(models.Model):
    user_id = models.ForeignKey('Profile')
    password = models.CharField(max_length=12, default='123456')

美味资源:

class ProfileResources(ModelResource):
    id = fields.CharField(attribute='id')

    class Meta:
        queryset = Profile.objects.all()
        resource_name = 'profile'

        filtering = {
            "id": ALL,
        }

我想创建一个函数,它可以通过仅使用一个资源同时将值保存到两个表中。我的问题是如何使用 ProfileResources 将值发布到 Profile 和 UserEbiz 模型中。

【问题讨论】:

  • 为什么不为 UserEbiz 模型创建资源...!
  • 好的。为 UserEbiz 模型创建资源后,下一步该怎么做。

标签: django tastypie


【解决方案1】:

你会想要这样的:

class UserEbizResource(ModelResource):
    user_id = fields.ToOneField(ProfileResources, attribute='user_id')

    class Meta:
        queryset = UserEbiz.objects.all()
        resource_name = 'userebiz'

        excludes = ['password']
        filtering = {
            "id": ALL,
        }

其他一些建议:

  • ProfileResources 重命名为ProfileResource
  • UserEbiz.user_id 重命名为UserEbiz.profile
  • 考虑使用 Django 的 User 模型或对其进行自定义,而不是完全自定义的模型

【讨论】:

    【解决方案2】:

    @sean-hayes 答案很好但是如果你真的想Post ProfileResource 上的数据而不是 UserEbiz 首先将 ProfileResource 更改为

    class ProfileResource(ModelResource):
        ebiz = fields.ToManyField(UserEbizResource, 'userebiz_set', readonly=True)
    

    注意首先您有一个ForeignKeyProfile。所以它是1:M for Profile to UserEbiz

    第二我已将readonly 设置为true,因为我将自己处理UserEbiz 数据。但是,如果您有 models.ForeignKey('Profile', blank=True, null=True),那么就像创建 M2M 数据一样,只需删除 readonly 属性即可。

    所以你可以override obj_create 自己处理ebiz 数据。代码可能看起来像

    def obj_create(self, bundle, **kwargs):
        ebiz = bundle.data.pop('ebiz', None)
        bundle = super(ProfileResource, self).obj_create(bundle, **kwargs)
        if not ebiz:
            return bundle
    
        ebiz.update(user_id=bundle.obj) # change it to user in model and here
        ebiz_res = UserEbizResource()
        ebiz_bundle = ebiz_res.build_bundle(data=ebiz)
        ebiz_res.obj_create(ebiz_bundle)
        return bundle
    

    【讨论】:

    • 我已经尝试过你的代码,但是我得到了这个错误 "error_message": "super(type, obj): obj must be an instance or subtype of type",
    • @nuriffah 您没有将资源实例传递给超类。你能用你的使用方式更新你的问题obj_create...!
    • 我已经解决了这个错误,但是当在 Profileresource 中发布成功但在 UserEbizResource 中没有发布时。数据没有保存到 UserEbiz 模型中。
    • @nuriffah 那是不可能的.. :) 你是否在 ebiz 中发送任何数据...比如 { "ebiz" : { "password" : "something"} }
    • 没有。我只是将数据发送到 ProfileResource。我应该怎么做才能提交到个人资料,然后再提交到 ebiz。
    猜你喜欢
    • 2012-10-15
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    相关资源
    最近更新 更多