0
希望這不是太難看,我剛剛開始從PHP轉移到Django,但我試圖圍繞模型繞過模型,並且不能完全找出如何解決這個問題。使用Meta類顯示來自ManyToManyField的零件列表
這裏是我想要做的事:
1)創建一個新的「配置」(設置RamConfig.size說16GB)
2)選擇其大小和數量從SIZE_CHOICES包括在16GB配置中;例如,假設我在16GB的「配置」中添加了8個2GB的「部件」。
3)保存配置。
上述工作很好,但現在我們有一個RamConfig,它是16GB(8)2GB「部件」。我希望每個2GB部分都引用資產,其中RamConfig.servermodel位於Asset.Servermodels中的「資產」模型中。
因此,如果16GB「配置」被拉起,它將顯示每個2GB「零件」的所有可用資產。我真的不確定這是否應該在模型或模板中完成;我只是試圖讓它現在在管理中正常運行。
from django.db import models
class Manufacturer(models.Model):
name = models.CharField(max_length=20,unique=1)
def __unicode__(self):
return self.name
class ServerModel(models.Model):
name = models.CharField(max_length=20,unique=1)
manufacturer = models.ForeignKey(Manufacturer)
def __unicode__(self):
return "%s %s" % (self.manufacturer, self.name)
class Asset(models.Model):
SIZE_CHOICES = (
('512MB', '512MB'),
('1GB', '1GB'),
('2GB', '2GB'),
('4GB', '4GB'),
('8GB', '8GB'),
('16GB', '16GB'),)
name = models.CharField(max_length=20)
sku = models.CharField(max_length=10,unique=1)
oneoff = models.BooleanField()
size = models.CharField(max_length=8, choices=SIZE_CHOICES)
servermodels = models.ManyToManyField(ServerModel)
#Returns a string containing the platforms this asset is linked to.
def used_on(self):
usedon = []
for servermodel in self.servermodels.all():
usedon.append(servermodel.__str__())
return ", ".join(usedon)
def __unicode__(self):
return self.size
class RamConfig(models.Model):
size = models.CharField(max_length=5, verbose_name="Configuration Size")
description = models.CharField(max_length=30)
servermodel = models.ForeignKey(ServerModel, verbose_name="Server Model")
assets = models.ManyToManyField(Asset, through='RamConfigPart')
def __unicode__(self):
return self.size
def total_parts(self):
return self.assets.all().count()
class RamConfigPart(models.Model):
SIZE_CHOICES = (
('512MB', '512MB'),
('1GB', '1GB'),
('2GB', '2GB'),
('4GB', '4GB'),
('8GB', '8GB'),
('16GB', '16GB'),)
config_size = models.CharField(max_length=8, choices=SIZE_CHOICES)
ramconfig = models.ForeignKey(RamConfig)
asset = models.ForeignKey(Asset)
quantity = models.PositiveIntegerField()
def __unicode__(self):
return self.asset.name
class Meta:
unique_together = ['ramconfig', 'asset']
感謝您的任何提示:]
這只是返回什麼存量資產,可用於指定配置的工具。所以,如果一臺服務器需要一個1GB DIMM,我想要返回所有1GB資產,而不是該服務器可以使用的資產。 它會是這樣的: 用戶:和雅,我需要4GB的RAM爲Optiplex220 服務器:太好了,您需要(4)1GB DIMM。適用於Optiplex220的1GB DIMM是4431-1331,3323-1312或1121-5554 儘管感謝您的建議。 – Zee 2011-12-14 23:37:16