how to copy data from model to another model in Django after filtering?

Viewed 95

here is the models:

class Rooms(models.Model):
    
    name=models.CharField(max_length=100)
    image=models.URLField()
    max_person=models.CharField(max_length=100)
    office=models.CharField(max_length=200)
    status=models.CharField(max_length=200)
    cost=models.CharField(null=True,max_length=250)
    roomId=models.CharField(max_length=100,null=True)
    Address= models.CharField(max_length=100,null=True)
    def __str__(self):
        return str(self.name)
    

class Available_Rooms(models.Model):
    users=models.ForeignKey(Rooms,on_delete=models.CASCADE)
    name=models.CharField(max_length=100)
    image=models.URLField()
    max_person=models.CharField(max_length=100)
    office=models.CharField(max_length=200)
    status=models.CharField(max_length=200)
    cost=models.CharField(null=True,max_length=250)
    roomId=models.CharField(max_length=100,null=True)
    Address= models.CharField(max_length=100,null=True)
    def __str__(self):
        return str(self.name)

at model "rooms" there is 100 objects (rooms)

and what I want filter it and list rooms that have maxperson = 4

availablity= Rooms.objects.filter(maxperson="4").all()

and want to to copy the rooms details to the other model "Available_Rooms"

any idea how that can be done? many thanks in advance

1 Answers

and want to to copy the rooms details to the other model Available_Rooms.

Please don't: it makes no sense to do that: you are introducing data duplication, which is an antipattern. This means that if you now want to change for example the name of a Room, you need to modify both the Rooms and the Available_Rooms. This will thus introduce a lot of extra logic to keep the rooms in sync.

What you can for example do is add a BooleanField that determines if the room is available, with:

class Room(models.Model):
    name = models.CharField(max_length=100)
    image = models.URLField()
    max_person = models.IntegerField()
    office = models.CharField(max_length=200)
    status = models.CharField(max_length=200)
    cost = models.IntegerField(null=True)
    room_id = models.CharField(max_length=100,null=True)
    address = models.CharField(max_length=100)
    available = models.BooleanField(default=False)
    
    def __str__(self):
        return str(self.name)

Then you can for example make all rooms available that have as max_person=4 with:

Room.objects.filter(max_person=4).update(available=True)

Note: normally a Django model is given a singular name, so Room instead of Rooms.


Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: room_id instead of roomId.

Related