Django Tastypie “ToManyField” in “parent” resource seems to break POST to chile resource

被刻印的时光 ゝ 提交于 2019-12-04 17:06:27

OK, I found my own answer. In EventInviteesResource

user = fields.ForeignKey(UserResource, 'invitee', full=True)

Needs to be the following in order to mirror my Django Model:

invitee = fields.ForeignKey(UserResource, 'invitee', full=True)

While this DOES seem logical, I must say that the "invitees" (notice the "s") error I was getting does NOT but oh well...

Bonus Answer, in EventResource, update:

invitees = fields.ToManyField('bbservices.api.EventInviteesResource', 'invitees', full=True)

To:

invitees = fields.ToManyField('bbservices.api.EventInviteesResource', 'invitees', related_name='event', full=True)

An now you can post to EventResource with invitees and have those created automatically as well. The post data would look like this:

{
    "store" : "/api/v1/store/2/", 
    "name" : "Yes again?", 
    "event_time" : "2013-02-06T18:30-3:00",
    "requires_confirmation" : true,
    "invitees" : [
                    {
                      "invitee" : "/api/v1/user/1/",
                      "confirmed" : true
                    }
                ]
}

So now my only doubt is...can anyone tell me why I cant use the PK syntax for FKs:

{ "store" : {"pk" : 2}, ...

This results in errors stating that fields for the Store object cannot be null as if it was try to create a new store object. If I use the URI path as below it works fine:

{ "store" : "/api/v1/store/2/", ...

But I would prefer not to have to pass back the full URI and I should have to. That is why I'm using the store_id trick in obj_create but its VERY kludgy...

Any ideas?

When you provide {"store":"/api/v1/store/2/"} you only specify the store value of an EventResource. But when you provide {"store": {"pk":2}} you do not only specify the value of store but also edit the store (save the related object). That is tastypie "style".

What we can do is to build a set of Javascript function that automatically convert from/to resource uri. Using existing Javascript MVC Frameworks like AgularJS or Backbone as Front End and Django Tastypie as Back End are very powerful.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!