扩展Django中的DICT模型字段
我需要一种方法,能够在Django模型中输入带有自动插入键的未指定数量的任意整数值。
它需要查看或至少可以正常工作:
{
"1":6,
"2":10,
"3":0,
...
"n":42
}
我希望有一个简单的解决方案,例如:
class Foo(models.Model):
title = models.CharField(max_length=100)
dictOfInts = {
models.AutoField(): models.IntegerField,
models.AutoField(): models.IntegerField,
models.AutoField(): models.IntegerField
...
# it would start with just one and automatically add more k-v pairs as nessary
}
#other fields ect
def __str__(self):
return self.title
不幸的是,我知道这行不通,并且不会发挥评论的建议,但是它需要对于最终用户而言。
我已经浏览了文档,并且发现那里的唯一解决方法是使用models.jsonfield()
,但这要求您输入DICT自己,这并不理想。我发现的另一种可能的方法是将dict和KV对分开,将它们与外键联系起来,但是我无法完全弄清楚如何整合它,即使可以的话,它似乎也很混乱。
如果您需要更多信息,请告诉我。
感谢任何帮助,谢谢。
编辑:还要注意,我目前正在使用管理页面输入项目,但最终将从前端(React)进行处理,以防万一更改任何内容。
I need a way to be able to enter an unspecified number of arbitrary, integer values with an auto-incrementing key into a dictionary in a django model.
It would need to look, or at least function, like this:
{
"1":6,
"2":10,
"3":0,
...
"n":42
}
I'm hoping there will be a simple solution like:
class Foo(models.Model):
title = models.CharField(max_length=100)
dictOfInts = {
models.AutoField(): models.IntegerField,
models.AutoField(): models.IntegerField,
models.AutoField(): models.IntegerField
...
# it would start with just one and automatically add more k-v pairs as nessary
}
#other fields ect
def __str__(self):
return self.title
Unfortunately, I know that doesn't work and wouldn't function how the comment suggests, but it would need to act like that for the end-user.
I've looked through the docs and the only workaround I found there was using models.JSONField()
, but that requires you to type out the dict yourself, which is not ideal. Another possible way that I found would be to separate the dict and the k-v pairs, linking them with a foreign key, but I couldn't quite figure out how to integrate it and it seemed very messy even if I could.
If you need any more info, just let me know.
Any help is much appreciated, thanks.
Edit: Also to note, I am currently using the admin page to enter items at the moment, but it will eventually be handled from the frontend (react), just in case that changes anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选项1,使用JSONFIELD的解决方案:
不幸的是,对于此方法,您每次都必须在列表中添加另一个值:
选项2,使用相关表:
这种方法的好处是,您不必考虑以前存储的其他值,只需为这个父母添加一个新孩子:
Option 1, solution with JSONField:
Unfortunately for this method, you will have to do some work everytime you want to add another value to the list:
Option 2, use related table:
The good thing for this method is that you do not have to think about the other, previous values stored before - just add a new child for this parent: