如何在django

时间:2015-11-17 06:28:01

标签: django python-2.7

enter image description here我正在开发基于django管理员的项目,现在我遇到了一件大事。我想在"item_issued"模型中添加一个名为user_profile的字段。 在"item issued"字段中有一个表格,其中包含3列"item_name","quantity" and "price"。我无法应用此项。您可以帮助我吗? 提前致谢

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望在指向ForeignKey的{​​{1}}中添加user_profile。您可以通过使用您提到的字段创建新模型item_issued来实现这一目标:

ItemIssued

现在,当您拥有class ItemIssued(models.Model): item_name = models.CharField(max_length=100) quantity = models.IntegerField() price = models.FloatField() 模型时,可以向ItemIssued添加ForeignKey(我假设模型名为user_profile):

UserProfile

之后,不要忘记运行

class UserProfile(models.Model):
     ...   # your existing fields
     item_issued = models.ForeignKey(ItemIssued)

答案 1 :(得分:0)

这是一个起点:

models.py

class ItemIssued(models.Model):
    item_name = models.CharField(max_length=50)
    quantity = models.IntegerField()
    models.DecimalField(max_digits=6, decimal_places=2) #use decimal field for price values.


class UserProfile(models.Model):
    # some other fields..
    issued_items = models.ManyToManyField("ItemIssued", related_name="+issued_items", null=True, blank=True)

如果您需要在Django Admin之外使用此字段,views.py

user = UserProfile.objects.get(username="ali")

new_issued_item = ItemIssued.objects.get(item_name="test_item")

user.issued_items.add(new_issued_item) #add 
user.issued_items.delete(new_issued_item) #delete

items = user.issued_items.all()  # get all issued items of user

我没有测试代码。但他们应该工作。