Here is my general solution shown with the standard [] brackets syntax. Setup:
- [top] is the parent resource with will have 0 or more children "[bottom]s".
- [bottom] is the child resource.
- An example is User having Blogs. In this case, a blog cannot exist without a User specified.
API.py
[bottom]s = fields.ToManyField([bottom]Resource, '[bottom]s', full=True, null=True)
class Meta:
queryset = [top].objects.all()
class [bottom]Resource(ModelResource):
class Meta:
queryset = [bottom].objects.all()
Models.py
pass
class [bottom](models.Model):
[top] = models.ForeignKey([top],related_name="[bottom]s")
API.py
blogs = fields.ToManyField(BlogResource, 'blogs', full=True, null=True)
class Meta:
queryset = User.objects.all()
class BlogResource(ModelResource):
class Meta:
queryset = Blog.objects.all()
Models.py
pass
class Blog(models.Model):
user = models.ForeignKey(User,related_name="blogs")
This works great for ToMany relationships, but in OneToOne relationships it puts your single related object within a 1-element array. Yet when I simply change your ToManyField declarations to ToOneFields instead I get a "RelatedManager has no attribute XYZ" error. This makes sense within Django, because we're getting a Manager instead of an actual object -- but is there a way to tell TastyPie to take the next step?
ReplyDeleteThe ForeignKey.related_name in the models.Model class must match the Tastypie REST API attribute. Otherwise, I see Tastypie fail silently with an empty list like "reverse_field": [].
ReplyDeleteThe definitions below must match the text "blog" exactly since Python is case sensitive. This is a really odd restriction!
blogs = fields.ToManyField(BlogResource, 'blogs', full=True, null=True)
and
user = models.ForeignKey(User,related_name="blogs")
It took me too long to find this! Thank you for the clear example. If the models were on the TastyPie docs as yours are here, it would have saved me a lot of time.
ReplyDelete