将 TastyPie ModelResource 添加到通过 Django OneToOne 关系连接的另一个 ModelResource
我有两个通过 OneToOne 关系连接的 django 模型,但我无法了解如何在 Tastypie ModelResource 中连接它们。
我不会发布一些新模型,而是借用 中定义的模型,包括子资源在 Django Tastypie API 中显示我不知道如何执行此操作的地方。使用 Ticket
和 TicketComment
模型,想象一下 TicketComment
是这样的:
class TicketComment(models.Model):
ticket = models.OneToOneField('Ticket')
而不是使用foreignkey字段。我已经看过使用 ToManyField
和 ToOneField
的文档以及类似上面的帖子。但这似乎不适用于我的情况,因为 Ticket
没有引用 TicketComment
。我想要做的是能够创建一个 API,在 Ticket
中列出 TicketComment
。 Tastypie 正确地抛出异常,指出 Ticket
模型中不存在 TicketComment
字段。有没有办法将漂亮的序列化 TicketComment
放入 Ticket
API 中?
I have two django models that are connected by a OneToOne relationship and I am having trouble seeing how to connect them in a Tastypie ModelResource.
Instead of posting some new models I will borrow the models defined in Including child resources in a Django Tastypie API to show where I am not getting how to do this. Using the Ticket
and TicketComment
models, imagine that the TicketComment
was like this:
class TicketComment(models.Model):
ticket = models.OneToOneField('Ticket')
instead of using the ForeignKey field. I have seen the docs as well as posts like the above which are using the ToManyField
and ToOneField
. But that doesn't appear to work in my situation since the Ticket
does not reference the TicketComment
. What I want to do is be able to create an API that lists the TicketComment
in the Ticket
. Tastypie rightly throws an exception saying that TicketComment
fields don't exist in the Ticket
model. Is there a way to get the nice serialized TicketComment
into the Ticket
API?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个 attribute arg 告诉 tastypie 应该使用哪个字段。 Ticket 通过反向关系引用 TicketComment。默认情况下,它将是小写的模型名称,因此在您的示例中它将是票证评论。但我建议您设置 related_name显式地在模型中添加 属性,以便您知道它将如何连接。
所以在你的美味馅饼中你应该这样做:
它会工作得很好。 OneToOneField 中的第二个参数是一个属性。
There is an attribute arg that tells tastypie what field it should use. Ticket is referenced TicketComment by reverse relation. By default it will be a lowercased model name so in your example it will be ticketcomment. But i recommend you to set a related_name attribute in your model explicitly so you will know how it will be connected.
So in your tastypie you should do this :
And it will work fine. The second arg in OneToOneField is a attribute.