K
K
kondratev-ad2022-03-02 17:50:39
PostgreSQL
kondratev-ad, 2022-03-02 17:50:39

How to make unique ForeignKey field values ​​in Django based on records in the database?

It is interesting to make restrictions either at the model level or in the admin panel (I work with models from there).
There are such models:

class ModelA(models.Model):
    name = models.CharField('имя модели А',  max_length=200)

class ModelB(models.Model):
    name = models.CharField('имя модели B',  max_length=200)

class ModelC(models.Model):
    name = models.CharField('имя модели C',  max_length=200)
    model_a = models.ForeignKey(ModelA, on_delete=models.SET_NULL, verbose_name='Модель А', null=True)
    model_b = models.ForeignKey(ModelB, on_delete=models.SET_NULL, verbose_name='Модель A', null=True)

Suppose there are two models A, two models B in the database:
A1 (id=1, name="One"),  A2 (id=2, name="Two")
B1 (id=1, name="One"),  B2 (id=2, name="Two")

How, when creating model C, to limit the choice of models A and B?
That is, I create a model C:
C1 (id=1, name="имя модели", model_a_id=1, model_b_id=1)

If I want to create a second model C with the same model A, the choice of model B would be limited to only id=2, because model C with model A (id=1) with model B (id=1) is already in the database.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2022-03-02
@Tomio

Look towards unique_together , validate_unique , or override the save method to validate.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question