如何在 Django 数据库模型的字段中存储字典 [英] How to store a dictionary in a Django database model's field

查看:43
本文介绍了如何在 Django 数据库模型的字段中存储字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!

推荐答案

可能最简洁的做法是创建另一个Products"表并建立多对多关系.(参见此处: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆