小编典典

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

django

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

例如,我有此代码:

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()

如果还有什么我要补充的请发表评论。谢谢!


阅读 805

收藏
2020-04-01

共1个答案

小编典典

我刚刚发现了django-jsonfield软件包,该软件包

是可重用的Django字段,可让您在模型中存储经过验证的JSON。

看起来是实现所需目标的可行选择。

2020-04-01