43
loading...
This website collects cookies to deliver better user experience
class Cpu(models.Model):
name = models.CharField(max_length=30)
numberOfCores = models.IntegerField(default=4)
frequency = models.FloatField(default=4.5)
def __str__(self):
return f"{self.name} {self.numberOfCores} - cores {self.frequency}GH"
class RamMemmory(models.Model):
quantity = models.IntegerField(default=4)
type = models.CharField(max_length=10)
def __str__(self):
return f"{self.quantity} GB {self.type}"
class PowerSupply(models.Model):
name = models.CharField(max_length=30)
power = models.IntegerField(default=100)
def __str__(self):
return f"{self.name} {self.power}W"
class Camera(models.Model):
name = models.CharField(max_length=30)
resolution = models.IntegerField(default=720)
def __str__(self):
return f"{self.name} {self.resolution}p"
class SpecsAbstract(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=100)
def __str__(self):
return f"{self.name} - {self.description}"
class PcSpecification(SpecsAbstract):
cpu = models.ForeignKey(Cpu, on_delete=models.SET_NULL, null=True)
ram = models.ForeignKey(RamMemmory, on_delete=models.SET_NULL, null=True)
powerSupply = models.ForeignKey(PowerSupply, on_delete=models.SET_NULL, null=True)
class LaptopSpecification(SpecsAbstract):
cpu = models.ForeignKey(Cpu, on_delete=models.SET_NULL, null=True)
ram = models.ForeignKey(RamMemmory, on_delete=models.SET_NULL, null=True)
camera = models.ForeignKey(Camera, on_delete=models.SET_NULL, null=True)
class Product(models.Model):
name = models.CharField(max_length=100)
spec = models.ForeignKey(SpecsAbstract, on_delete=models.RESTRICT)
def __str__(self):
return f"{self.name}"
>>> Product.objects.first( ).spec
<SpecsAbstract: sample specification of laptop - test>
>>> Product.objects.first( ).spec
<LaptopSpecification: sample specification of laptop - test>
pip install django-polymorphic
, add it in settings.py
and change the SpecsAbstract class.from polymorphic.models import PolymorphicModel
class SpecsAbstract(PolymorphicModel):
name = models.CharField(max_length=100)
description = models.CharField(max_length=100)
def __str__(self):
return f"{self.name} - {self.description}"
>>> SpecsAbstract.objects.all( )
<PolymorphicQuerySet [
<PcSpecification: sample specification of PC - test>,
<LaptopSpecification: sample specification of laptop - test>
]>
>>> SpecsAbstract.objects.instance_of(PcSpecification)
<PolymorphicQuerySet [<PcSpecification: sample specification of PC - test>]>
>>> SpecsAbstract.objects.not_instance_of(PcSpecification)
<PolymorphicQuerySet [<LaptopSpecification: sample specification of laptop - test>]>
>>> SpecsAbstract.objects.all( ).non_polymorphic( )
<PolymorphicQuerySet [
<SpecsAbstract: sample specification of PC - test>,
<SpecsAbstract: sample specification of laptop - test>
]>