如何在Django数据库模型的字段中存储字典 [英] How to store a dictionary in a Django database model's field
问题描述
我需要在模型的字段中保存一个字典。如何做?
I need to save a dictionary in a model's field. How do I do that?
例如我有这个代码:
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 =,所以它将一些随机产品从我的产品模型保存到这个账单?
What do I write for "bill_products=" so it saves some random products, from my Product model to this bill?
这是账单的模型描述:
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()
如果还有什么我应该添加的只是留下评论。谢谢!
If there's anything else i should add just leave a comment. Thanks!
推荐答案
可能最干净的事情是创建另一个产品表,并拥有多对多关系。 (见这里: https:// docs。 djangoproject.com/en/dev/topics/db/models/#many-to-many-relationships 。在文档中,他们使用了具有许多浇头的比萨饼的例子。)
Probably the cleanest thing to do would be to create another "Products" table and have a many-to-many relationship. (See here: https://docs.djangoproject.com/en/dev/topics/db/models/#many-to-many-relationships . In the docs they use the example of a pizza having many toppings.)
另一个选项是序列化您的bill_products。在这种情况下,您可以执行以下操作:
The other option would be to serialize your bill_products. In that case, you'd do something like:
bill_products = json.dumps([rand_products])
这将在for循环之外(尽管在上面的例子中,rand_products只是一个值,需要修复)。
This would be outside of the for loop (although, in your example above, rand_products is only a single value, so you'll need to fix that).
这篇关于如何在Django数据库模型的字段中存储字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!