Django.fun

Change boolean data when adding new registration

in this code i want change a boolean data of room when adding new registration For example: when i add new registration in django admin the boolean data of room change to False

please can u help in it

from django.db import models

from django.contrib.auth.models import User


class Rooms(models.Model):
    room_num = models.IntegerField()
    room_bool = models.BooleanField(default=True)
    category = models.CharField(max_length=150)

    def __str__(self):
        return f'{self.room_num}'

    class Meta:
        verbose_name = 'Room'


class Registration(models.Model):
    rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    admin = models.ForeignKey(User, on_delete=models.CASCADE)
    pasport_serial_num = models.CharField(max_length=100)
    birth_date = models.DateField()
    img = models.FileField()
    visit_date = models.DateTimeField()
    leave_date = models.DateTimeField()
    guest_count = models.IntegerField()

    def func(self):
        room = Rooms.objects.filter(room_bool=True)
        for i in room:
            if i.room_num == int(self.rooms):
                i.room_bool = False #this should change when adding new registration
                i.save()

You should use Django's signals for that. Just create signals.py in your app's folder and do that:

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Registration


@receiver(post_save, sender=Registration)
def create_profile(sender, instance, created, **kwargs):
    if created:
        instance.rooms.room_bool = False
        instance.rooms.save()

and add to your apps.py file in same app:

from django.apps import AppConfig


class YourAppConfig(AppConfig):
    name = 'your_app'

    def ready(self):
        import your_app.signals

That signal will change proper Registration related Rooms object's room_bool to False when it was saved during creation.

PS always name your model with singular version. Look how awfully looks Rooms when you actually talk about single room ;)

you can override the save method of the Registration class to be called every time a Registration object has been created or updated.

class Registration(models.Model):
...
    def save(self, *args, **kwargs):
        if not self.pk:
            self.rooms.room_bool = False
            self.rooms.save()
            
        return super().save(*args,**kwargs)

the if condition is for checking creation or updating.

if self.pk for the creation and else for updating the object.

Tutorials

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

Обработка периодических задач в Django с помощью Celery и Docker

View all tutorials →