0

Unsimilar to for example this case I am trying to allow only one entry in a database for one user:

class Station(models.Model):
    serial = models.CharField("serial", max_length = 31, unique = True)
    user = models.ForeignKey(User, on_delete = models.CASCADE, )

What I want is that one user can only have zero or one Station (serial).

xtlc
  • 1,070
  • 1
  • 15
  • 41

2 Answers2

1

This can be achieved using a one-to-one relationship. This means a user can have zero or exactly one station.

class Station(models.Model):
    serial = models.CharField("serial", max_length = 31, unique = True)
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
    )
Nepo Znat
  • 3,000
  • 5
  • 28
  • 49
1

You can set unique=true on your ForeignKey, but you do have wrong relationship type as you should have One-to-one

A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object.

class Station(models.Model):
    serial = models.CharField("serial", max_length=31, unique=True)
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        null=True,
        blank=True
    )
iklinac
  • 14,944
  • 4
  • 28
  • 30