扩展Django中的DICT模型字段

发布于 2025-02-10 17:27:36 字数 871 浏览 1 评论 0原文

我需要一种方法,能够在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宫墨修音 2025-02-17 17:27:36

选项1,使用JSONFIELD的解决方案:

class AJsonModel(models.Model):
    name = models.CharField(null=True, max_length=255)
    data = models.JSONField(null=True)

    def __str__(self):
        return f"A list of {[n for n in self.data]}" 
data = [10, 20, 30, 40, 50]
dict_data = {k:v for (k, v) in enumerate(data, 1)}

m = AJsonModel.objects.create(name="One", data=dict_data)
m.save()

不幸的是,对于此方法,您每次都必须在列表中添加另一个值:

c = AJsonModel.objects.get(id=1)
values = list(c.data.values())
values.append(60)
c.data = {k:v for (k, v) in enumerate(values, 1)}
c.save()

选项2,使用相关表:

class AJsonModelWithChild(models.Model):
    name = models.CharField(null=True, max_length=255)

    def __str__(self):
        return f"{self.name}"

class GrowingChild(models.Model):
    value = models.IntegerField(default=0)
    parent = models.ForeignKey(AJsonModelWithChild, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.id}: {self.value}"

这种方法的好处是,您不必考虑以前存储的其他值,只需为这个父母添加一个新孩子:

parent = AJsonModelWithChild.objects.create(name="Two")
parent.save()
child = GrowingChild.objects.create(value=100, parent=parent)
child.save()

Option 1, solution with JSONField:

class AJsonModel(models.Model):
    name = models.CharField(null=True, max_length=255)
    data = models.JSONField(null=True)

    def __str__(self):
        return f"A list of {[n for n in self.data]}" 
data = [10, 20, 30, 40, 50]
dict_data = {k:v for (k, v) in enumerate(data, 1)}

m = AJsonModel.objects.create(name="One", data=dict_data)
m.save()

Unfortunately for this method, you will have to do some work everytime you want to add another value to the list:

c = AJsonModel.objects.get(id=1)
values = list(c.data.values())
values.append(60)
c.data = {k:v for (k, v) in enumerate(values, 1)}
c.save()

Option 2, use related table:

class AJsonModelWithChild(models.Model):
    name = models.CharField(null=True, max_length=255)

    def __str__(self):
        return f"{self.name}"

class GrowingChild(models.Model):
    value = models.IntegerField(default=0)
    parent = models.ForeignKey(AJsonModelWithChild, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.id}: {self.value}"

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:

parent = AJsonModelWithChild.objects.create(name="Two")
parent.save()
child = GrowingChild.objects.create(value=100, parent=parent)
child.save()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文