【发布时间】:2015-02-25 16:55:42
【问题描述】:
我有两个模型(和一个抽象模型):用户、法师和角色。法师从角色“继承”。
Character 有一个 updated_date 字段,我正在尝试查看用户法师更新的最新日期:
class UserSerializer(serializers.ModelSerializer):
mage_by_user = serializers.PrimaryKeyRelatedField(
many=True, queryset=Mage.objects.all())
mage_last_updated = serializers.ReadOnlyField(
source='mage_by_user.updated_date')
class Meta:
model = User
fields = ('id', 'username', 'mage_by_user', 'mage_last_updated',)
但由于某种原因,'mage_last_updated' 字段没有出现!如果我删除'mage_by_user',那么它会出错,抱怨'mage_last_updated' 字段需要它存在。所以它在某个地方认出了它。
我该如何解决这个问题?我该如何解决?
编辑:
为了这个问题,这里是经过一些编辑的 json(即,我插入了 mage 对象,以显示 updated_date 字段)
{
"id":1,
"username":"admin",
"mage_by_user":[{
"id":3,
"player":"admin",
"name":"gandalf",
"sub_race":"Foo",
"faction":"Foo",
"is_published":false,
"updated_date":"2015-02-11T16:13:16.229890Z",
"power_level":1,
"energy_trait":7,
"virtue":"prudence",
"vice":"lust",
"morality":7,
"size":5,
"arcana":{
"Matter":0,
"Death":0,
"Fate":1,
"Mind":0,
"Prime":0,
"Forces":0,
"Spirit":0,
"Time":0,
"Space":0,
"Life":0
},
"mental_attributes":{
"Wits":0,
"Intelligence":1,
"Resolve":0
},
"physical_attributes":{
"Dexterity":0,
"Stamina":0,
"Strength":0
},
social_attributes":{
"Composure":0,
"Presence":0,
"Manipulation":0
},
"mental_skills":{
"Politics":0,
"Academics":1,
"Crafts":0,
"Medicine":0,
"Occult":0,
"Science":0,
"Investigation":0,
"Computer":0
},
"physical_skills":{
"Survival":0,
"Athletics":0,
"Weaponry":0,
"Stealth":0,
"Larceny":0,
"Brawl":0,
"Drive":0,
"Firearms":0
},
"social_skills":{
"Subterfuge":0,
"Expression":0,
"Socialize":0,
"Streetwise":0,
"Animal Ken":0,
"Persuasion":0,
"Empathy":0,
"Intimidation":0
}
}]
}
此外,正如 Django 所抱怨的那样,对于只读字段 mage_last_updated,添加 many=True 是不正确的。这里mage_by_user是用户“拥有”的法师列表。
【问题讨论】:
-
不应该
mage_last_updated有many=True,因为你得到了mage_by_user的列表吗? -
@SamRad 我只想要最新的法师日期,而不是全部。它仍然没有解释为什么它不存在。
-
你能发布一个你的输出/模型的例子吗?
mage_by_user是否有updated_date字段? -
@Samrad 我明天会仔细检查,但他们都应该有一个作为自动字段。我在打电话,但这里有一个输出问题:stackoverflow.com/q/28700626/1075247
-
@SamRad 我的编辑有帮助吗?
标签: django django-rest-framework