Please excuse the title but I'm not sure howto put this into words. I have a model "card" and a model "computer":
class card(models.Model):
name=models.CharField(
verbose_name = 'Name',
max_length=50,
null=True,
blank=True,
)
serial=models.CharField(
verbose_name = 'Serial',
max_length=50,
null=True,
blank=True,
)
class computer(models.Model):
name=models.CharField(
verbose_name = 'Name',
max_length=50,
null=True,
blank=True,
)
slot1 = models.OneToOneField(
'card',
related_name='cardslot1',
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name = 'Slot 1',
)
slot2 = models.OneToOneField(
'card',
related_name='cardslot2',
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name = 'Slot 2',
)
(Of course that this computer model is invalid) The cards are unique and should only be allowed to be used in one slot - of any computer. What's the best way to achieve this? I was thinking about a in-between table, something like
card n-1 cardcomputer n-1 computer
but I'm hoping there's a better way I'm not seeing right now. Thanks
CodePudding user response:
Use the constraints meta option for your model.
from django.db import models
from django.db.models import CheckConstraint, Q
class computer(models.Model)
class Meta:
constraints = [
CheckConstraint(
check = ~Q(slot1=slot2),
name = 'unique_slot',
),
]
CodePudding user response:
Yagus answer is correct, but here's a pure model alternative.
class Card(models.Model):
name = models.CharField(
verbose_name='Name',
max_length=50,
null=True,
blank=True,
)
serial = models.CharField(
verbose_name='Serial',
max_length=50,
null=True,
blank=True,
)
class Slot(models.Model):
card = models.OneToOneField(Card,
on_delete=models.SET_NULL,
null=True,
blank=True
)
computer = models.ForeignKey('Computer',
on_delete=models.CASCADE,
related_name='slots'
)
class Computer(models.Model):
name = models.CharField(
verbose_name='Name',
max_length=50,
null=True,
blank=True,
)
This way you have flexibility to add/change slots per computer in the admin panel and things are imho more readable than the constraints.
You can still access Computer.slots
thanks to the related name.