[英]Django Designing Model : Item/Inventory/User
I would like to ask some advice on Modeling a specific model behavior. 我想就建模特定模型行为提出一些建议。 Basically I have a model Item.
基本上我有一个模型项目。 It describes the name and description of an item.
它描述了项目的名称和描述。
I have a inventory, which should hold a "List" of items, considering the quantity of each item should be specified in the inventory. 我有一个库存,应该持有一个“列表”的项目,考虑到应该在库存中指定每个项目的数量。
Each User
should have one unique inventory. 每个
User
应该有一个唯一的库存。
Here's what I'm trying to do: 这是我正在尝试做的事情:
class User(models.Model):
name = models.CharField(max_length=100)
invetory =models.ForeignKey(inventory,on_delete=models.CASCADE)
class item(models.Model):
name =models.CharField(max_length=40)
description = models.TextField(max_length=200)
value = models.FloatField()
class inventory(models.Model):
?
I'm not sure if this is the right approach. 我不确定这是不是正确的做法。
class User(models.Model):
name = models.CharField(max_length=100)
class Inventory(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
class Item(models.Model):
name =models.CharField(max_length=40)
description = models.TextField(max_length=200)
value = models.FloatField()
invetory =models.ForeignKey(Inventory,on_delete=models.CASCADE)
This should work as per your specification. 这应该按照您的规范工作。 We have tied up inventory to a user and each item will have a foreign key to Inventory table.
我们已将库存与用户捆绑在一起,每个项目都有一个到库存表的外键。
Now you can do 现在你可以做到
1. To access inventory you can do `user.inventory`
2. To get a list of items `user.inventory.item_set`
3. You should use the `post_save` signal to create the inventory object.
class inventory(models.Model):
user = models.ForeignKey(User, default=User.objects.first())
item = models.ForeignKey(Item, default=Item.objects.first())
count = models.IntegerField(default=0)
I think this would make a better design. 我认为这会有更好的设计。
You should use many-to-many relations. 你应该使用多对多的关系。 First of all you should delete the FK from the User model.
首先,您应该从User模型中删除FK。 Then create a separate model for items and finally link many users to many items (one user can handle multiple items and one item can belong to multiple users).
然后为项目创建单独的模型,最后将许多用户链接到多个项目(一个用户可以处理多个项目,一个项目可以属于多个用户)。 Something like that:
像这样的东西:
class User(models.Model):
name = models.CharField(max_length=100)
class item(models.Model):
name =models.CharField(max_length=40)
class inventory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(item, on_delete=models.DO_NOTHING)
quantity = models.FloatField()
PS Class names should use PascalCase convention https://www.python.org/dev/peps/pep-0008/?#class-names PS类名称应使用PascalCase约定https://www.python.org/dev/peps/pep-0008/?#class-names
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.