Home > front end >  Change boolean data when adding new registration
Change boolean data when adding new registration

Time:05-23

In this piece of code l want to change the boolean data of room when adding new registration For example: when l add new registration in django admin the boolean data of room should change to False

from django.db import models

from django.contrib.auth.models import User

#This class Rooms for adding rooms
class Rooms(models.Model):
    room_num = models.IntegerField()
    room_bool = models.BooleanField(default=True) #if room_bool = True room is open, else closed.
    category = models.CharField(max_length=150)

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

    class Meta:
        verbose_name = 'Room'

#This class Registration for visitors, to open room for the them
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()

CodePudding user response:

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 ;)

CodePudding user response:

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.

  • Related