使用Django 1.7 .
我有一个我要序列化的模型类 Topic
. Topic
有一个属性 Creator
,它是类 UserProfile
的ForeignKey . 序列化的输出给我以下字符串:
'{"fields": {"building": 1, "title": "Foobar", "created": "2015-02-13T16:14:47Z", "creator": 1}, "model": "bb.topic", "pk": 2}'
我希望 key
"creator"说出与 UserProfile
相关联的用户名(与现在相反,它给出了与 UserProfile
相关联的pk值 . 用户名保存在OneToOneField中,带有 django.contrib.auth.models
class User
.
我试图实现一个UserProfileManager,但要么我做错了,要么以下不是一个合适的策略:
def get_by_natural_key(self, user, picture, company):
return self.get(user_id=user.id, user_pk=user.pk, username=user.get_username, picture=picture, company=company)
最后,我环顾四周,发现指向这个:https://code.google.com/p/wadofstuff/wiki/DjangoFullSerializers但它说最后一次更新是在2011年,所以我假设还有其他的东西 .
谢谢 . 任何帮助深表感谢 .
1 回答
它看起来你没有实现使用自然键序列化
UserProfile
所需的所有代码 .实际上,在反序列化对象时会调用
get_by_natural_key
方法 . 如果您希望使用自然键而不是pk
序列化它,则应该为模型提供natural_key
方法 .就像是:
现在,如果序列化一个
Topic
实例:你应该得到类似于的输出:
假设在其用户配置文件中存在名为ACME Inc.的公司的虚拟用户 .
希望这可以帮助 .