我知道网上有大量的资源可以解决这个问题,但我觉得我的模型的情况非常奇怪,我知道语法可能会变得非常混乱,所以我只是不知道该怎么做。
所以我正在为一家冰淇淋公司创建软件来跟踪他们的库存。我的模型是这样的:
class sizeCounts (models.Model):
class Meta:
verbose_name = "Size Count"
verbose_name_plural = "Size Counts"
#Just to label a collection of sizes with the corresponding flavor so it's not confusing!
item_Flavor_Choices = [('CHOCOLATE','chocolate'),('VANILLA', 'vanilla'),('COOKIESNCREME', 'cookiesncreme'), ('STRAWBERRY', 'strawberry')]
item_Flavor = models.CharField(max_length=100, choices = item_Flavor_Choices, default='chocolate')
half_Pint_Count = models.IntegerField(default=30)
one_Quart_Count = models.IntegerField(default=30)
pint_Count = models.IntegerField(default=30)
half_Gallon_Count = models.IntegerField(default=30)
gallon_Count = models.IntegerField(default=30)
def __str__(self):
return 'Half Pint: %s, Quart: %s, Pint: %s, Half Gallon: %s, Gallon: %s' % (self.half_Pint_Count, self.one_Quart_Count,
self.pint_Count, self.half_Gallon_Count, self.gallon_Count)
class item (models.Model):
class Meta:
verbose_name = "Item"
verbose_name_plural = "Items"
item_Flavor_Choices = [('CHOCOLATE','chocolate'),('VANILLA', 'vanilla'),('COOKIESNCREME', 'cookiesncreme'), ('STRAWBERRY', 'strawberry')]
item_Flavor = models.CharField(max_length=100, choices = item_Flavor_Choices)
size_Counts = models.ForeignKey(sizeCounts, on_delete=models.CASCADE, default = None)
def __str__(self):
return self.item_Flavor
可以看到,我有一个item模型和一个sizeCounts模型。每个项目都有一种风格和每种尺寸的固定数量(因此有一个指向sizeCounts的外键)。假设我有一件巧克力口味的物品。我如何引用该对象的sizeCounts?例如,我如何能够根据某个项目对象的一个属性获取该项目对象,然后引用该项目对象的其他属性?我想利用这些信息把库存放在前端。
任何帮助都是感激的。谢谢你!
这很简单,使用django queryset API来检索你想要的对象。
# Note that 'objects' is a manager and is used to make queries for a model.
item_1 = item.objects.get(item_Flavor="Chocolate")
# Then use the dot notation to access the object's fields, such as the 'attached' sizeCounts object in the size_Counts field.
item_1.size_Counts
# If you want to 'use/access' the fields/columns of the sizeCounts object, then do this:
item_1.size_Counts.half_Pint_Count # This will get you the value at this field.
在这里阅读更多关于Django Queryset API和对象管理器的信息:
- https://docs.djangoproject.com/en/3.2/ref/models/querysets/
- https://docs.djangoproject.com/en/3.2/topics/db/queries/
- https://docs.djangoproject.com/en/3.2/topics/db/managers/
最后,考虑像这样重命名你的模型,以使它们更容易被识别为模型:SizeCount项目