[Answered ]-Django model allow only once in many

0👍

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.

1👍

Use the constraints meta option for your model.

from django.db import models
from django.db.models import CheckConstraint, Q

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',
    )

    class Meta:
        constraints = [
            CheckConstraint(
                check = ~Q(slot1=slot2), 
                name = 'unique_slot',
            ),
        ]
👤yagus

Leave a comment