使用Django Rest框架发布列表 [英] posting a List using Django Rest Frameworks
问题描述
使用DRF的新功能。好奇你们有什么方法用于存储列表....我试图实现新添加的 ListField ,但我无法使其工作。我使用MySql作为数据库。我认为有一个DRF具体的实现方法。
New to using DRF. Curious as to what approaches some of you have used regarding storing a List.... I tried to implement the newly added ListField but I was not able to get it working. I'm using MySql as the db. I figured there was a DRF-specific way of achieving this.
例如,说这是预期的输出:
For example, say this is the expected output:
{
"somenames": ["james", "jim"],
"somekey": "username",
}
models.py
models.py
class StringListField(serializers.ListField):
child = serializers.CharField()
class SomeClass(models.Model):
somenames = StringListField,
somekey = models.CharField(max_length=140, default='username')
def publish(self):
self.save()
def __str__(self):
return self.somekey
serializers.py
serializers.py
class MentionSerializer(serializers.ModelSerializer):
class Meta:
model = Mention
fields = ('somekey', 'somenames')
我可以实现的一个选项是将列表存储为单独的表,然后将其反映在表中将它们嵌入到外键
或 ManyToManyField
中。感谢任何建议。
One option I could implement is just storing the List as a seperate table then reflecting them in the table I need them to nest them in with Foreign Key
or ManyToManyField
. Thanks for any suggestion.
推荐答案
我使用这个
deep_link = serializers.ListSerializer(child=serializers.CharField())
它基本上是你的捷径。您的代码的问题是您将模型与串行器混淆。该模型是您的数据的数据库表示。该模型不指定序列化程序。串行器是您的模型来自数据库的序列化表示,主要用于数据传输。
it's basically a shortcut of yours. The problem with your code is that you are confusing Models with Serializers. The Model is the database representation of your data. The model does not specify serializers. The serializer is the serialized representation of your model coming from the DB, used mostly for data transfer.
class SomeClass(models.Model):
somenames = StringListField
somekey = models.CharField(max_length=140, default='username')
在这里,你告诉你的模型,你的Django模型的字段somenames是类型serializers.ListSerializers。这不是你想要的如果要将模型链接到字符串列表,您需要创建一个ManyToMany关系或任何您需要的。以下示例
here, you are telling your model that your Django model's field "somenames" is of type serializers.ListSerializers. That is not what you want. If you want to link a model to a list of strings you need to create a ManyToMany relationship or whatever you need. Below an example
class Name(models.Model):
name = models.CharField(max_length=100)
class SomeClass(models.Model):
somekey = models.CharField(max_length=100)
somenames = models.ManyToManyField(Names)
然后在您的序列化程序中,您将有
Then in your serializers you will have
class NameSerializer(serializers.ModelSerializer):
name = serializers.CharField()
class SomeClassSerializer(serializers.ModelSerializer):
somenames = NameSerializer(many=True)
somekey = serializers.CharField()
class Meta:
model = SomeClass
这篇关于使用Django Rest框架发布列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!