gpt4 book ai didi

python - Django - 序列化 parent 协会

转载 作者:行者123 更新时间:2023-11-29 02:52:51 26 4
gpt4 key购买 nike

我正在尝试从一对多关系创建一个序列化的 RESTful 响应。

我有一张表Lexicon,主键lexicon_id,我还有一张表lexicon_attributes,主键lexicon_attribute_id,外键lexicon_id

class Lexicons(models.Model):
"""
Holds all words
"""
lexicon_id = models.BigIntegerField(primary_key=True)
word = models.TextField(blank=True, null=True)
date_created = models.DateTimeField(blank=True, null=True)
date_modified = models.DateTimeField(blank=True, null=True)

class Meta:
managed = True
db_table = 'lexicons'

class LexiconAttributes(models.Model):
class Meta:
managed = True
db_table = 'lexicon_attributes'

lexicon_attribute_id = models.AutoField(primary_key=True)
lexicon_id = models.ForeignKey('Lexicons', db_column='lexicon_id', related_name="lexicon_attributes")
is_verb = models.CharField(max_length=1, blank=True, null=True)
is_plural = models.CharField(max_length=1, blank=True, null=True)
is_past_tense = models.CharField(max_length=1, blank=True, null=True)

序列化器

class LexiconAttributesSerializer(serializers.ModelSerializer):
class Meta:
model = LexiconAttributes
fields = '__all__'

class LexiconsSerializer(serializers.ModelSerializer):
lexicon_attributes = LexiconAttributesSerializer(source='*', many=False)
class Meta:
model = Lexicons

当我请求/lexicons/2/时

{
“lexicon_id”:2,
“词典属性”:{
“lexicon_id”:2
},
“字”:“电脑”,
“创建日期”:“2015-07-30T20:29:19Z”,
“修改日期”:“2015-07-30T20:29:19Z”
}
如何获取 lexicon_attributes 表中的其他字段

仅供引用,我进入 Django 的第二周,我的应用程序最初是在 Cakephp3 中完成的

最佳答案

类 LexiconsSerializer(序列化器.ModelSerializer):
lexicon_attributes = LexiconAttributesSerializer()
类元:
模型 = 词典
字段 = '__all__'

3天后为我解决了问题

关于python - Django - 序列化 parent 协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33862397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com