我需要在模型字段中保存字典。我该怎么做?
例如我有这个代码:
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/