M
M
maniacus262019-02-21 11:37:34
Django
maniacus26, 2019-02-21 11:37:34

How to check if the generated value exists in another Django db table?

there are 2 models:

class U (models.Model):
    id = models.AutoField(primary_key=True)
    created_at = models.DateTimeField(auto_now_add=True)
    author = models.CharField(max_length=3000, blank=True, null=True)
    name = models.CharField(max_length=18, null=True, blank=True)

class U_blocked (models.Model):
    name_blocked = models.CharField(max_length=18, help_text="блокированный")

Periodically, "some forbidden values" are entered into the U_blocked model through the admin panel that cannot be used in the U model.
When entering information through the form of the U model in the "name" field, I need to check for the presence of the entered value in U_blocked.name and if the values ​​match, then throw it away error.
Please tell me how can I implement such a check.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yura Khlyan, 2019-02-21
@maniacus26

if U_blocked.objects.filter(name_blocked=cleaned_data.get('name')).exists():
    raise ValidationError

H
harabudjasim, 2019-02-21
@harabudjasim

If I understand everything correctly, then you need to prevent adding records with text from the "locked" table to the database.
Try adding a check in the pre_savesignal. Here is an example mechanism.
https://stackoverflow.com/a/6462188
If you need to prevent save - just throw an exception.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question