python - 如何在 Django 数据库模型的字段中存储字典

标签 python django dictionary model save

我需要在模型字段中保存字典。我该怎么做?

例如我有这个代码:

def create_random_bill(self):
    name_chars = re.compile("[a-zA-Z0-9 -_]")
    bill_name = "".join(random.choice(name_chars for x in range(10)))
    rand_products = random.randint(1,100)
    for x in rand_products:
        bill_products = 
    new_bill = Bill.new(name=bill_name, date=datetime.date, products=bill_products)
    new_bill.save()

我为“bill_products=”写什么,这样它可以保存一些随机产品,从我的产品模型到这个账单?

这是账单的型号说明:

class Bill(models.Model):
    name = models.CharField(max_length=255)
    date = models.DateTimeField(auto_now_add=True)
    products = models.ManyToManyField(Product, related_name="bills")

还有产品型号说明:

class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.IntegerField()

如果还有什么我应该添加的,请发表评论。谢谢!

最佳答案

我刚刚发现 django-jsonfield包,其中

is a reusable Django field that allows you to store validated JSON in your model.

看起来是实现您想要的可行选择。

关于python - 如何在 Django 数据库模型的字段中存储字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9686409/

相关文章:

json - VBA/JIRA/JSON : add new key/value to dictionary parsed from a JSON

python - 如何在 SQLAlchemy 中为 MSSQL 设置架构?

python - 读取 csv 文件中的 n 个表以分隔 pandas DataFrame

python - 如何重构此 django 查询以不选择每个单独的对象?

python - 如何在 Django Rest Framework 中返回 403 错误的数据?

python - python pyqt5 类引用

python - 在 Pyramid .ini 文件中配置不同的电子邮件后端

c++ - 将 Python 的 Django 集成到 C++ 应用程序中

c# - C++-STL映射和Boost的unordered_map的更好替代方案?