[英]Django and Tastypie, overwrite a specific field in a OnToMany field
我們有一個舊版的移動應用程序,如果它與字段不匹配,則會崩潰。 它是在API的早期版本上-因此,我所要做的就是將API中的單一用法覆蓋為對舊版應用程序來說是安全的值。 (我無法更改較新應用程序的數據庫中的值)。
經過大量研究,我發現可以使用脫水功能並正確設置該值。 我的控制台中的值正在更改-但是,瀏覽器輸出未獲取更改。 我有點難過。
這是完整的模型資源。 請原諒我的python-盡管我是個狂熱的粉絲-這不是我的正常踐踏之地。
class SectionResource(ModelResource):
articles = fields.ToManyField('app.api.ArticleResource', "articles_sections", null=True, full=True)
class Meta:
queryset = Section.objects.all()
resource_name = "sections"
filtering = {
'id': ['exact'],
}
def dehydrate(self, bundle):
for i in range(len(bundle.data['articles'])):
if bundle.data['articles'][i].obj.template == "Program":
bundle.data['articles'][i].obj.template = "Template"
#print bundle.data['articles'][i].obj.template #updated in print but not browser
return bundle
您確實在打印與分配相同的內容,但是article是否具有要序列化的obj屬性?
您的版本以及建議的修復程序:
def dehydrate(self, bundle):
for i in range(len(bundle.data['articles'])):
if bundle.data['articles'][i]["template"] == "Program":
bundle.data['articles'][i]["template"] = "Template"
return bundle
固定重寫版本:
def dehydrate(self, bundle):
for article in filter(lambda a: a.get("template") == "Program", bundle.data.get('articles', [])):
article["template"] = "Template"
return bundle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.