Hopefully this isn’t too ugly, I just started moving over from PHP to Django, but I’m trying to wrap my head around models and can’t quite figure out how to approach this.
Here is what I’m trying to do:
1) Create a new “configuration” (set RamConfig.size to say 16GB)
2) Select which sizes and quantities from SIZE_CHOICES to include in the 16GB config; For example, lets say I added eight 2GB “parts” to the 16GB “config”.
3) Save config.
The above works just fine, but now we have a RamConfig that is 16GB with (8) 2GB “parts”. I want each of these 2GB parts to reference assets from the “Asset” model where RamConfig.servermodel is in Asset.Servermodels.
So, if the 16GB “config” is pulled up, it will display all available assets for each 2GB “part”. I’m really not sure if this should be done in the model or the template; I’m just trying to get it to function properly in admin for now.
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']
Thanks for any tips :]
I would re-think that model structure if I were you. And if your problem is to represent how much RAM and how many slots that RAM takes up on the server, I would use two fields to solve that.
Then you could in your unicode method do something like: