0

Need somehow to limit in models ForeignKey to one from available choices. It's my models :

class CustomCompany(models.Model):
name = models.CharField(max_length=30,
        default=None,
        unique=True
        )
teams = ListCharField(
    base_field=models.CharField(max_length=15),
    size=15,
    max_length=(15*16),
    default=["Owners"],
    unique=True
)


class CustomUser(AbstractUser):
company = models.ForeignKey(CustomCompany,
        on_delete=models.CASCADE,
        default='None',
        to_field='name',
        related_name='company'
        )
team = models.ForeignKey(CustomCompany,
        on_delete=models.CASCADE,
        default='Owners',
        to_field='teams',
        related_name='team',
        )

And from this, I have issue with "team" model. Cause to team model assignment all choices, but I want to select only one from available. Someone had this issue? Is it possible to limit this ForeignKey to only one choose? Thx

Manish Iarhovich
  • 183
  • 1
  • 10

1 Answers1

0

AFAIK you cannot restrict this at the database level. A foreign key is defined as a relation from a row of one database table to a row of another. It's the responsibility of the higher level code do make sure that the creation of such relations is sensible.

You can restrict the choices available to the user in a Django Form. You use the queryset argument to a ModelChoiceField. See this answer.

nigel222
  • 7,582
  • 1
  • 14
  • 22