0

I have a model, which contains some fields, based on the one of the field value in the model, we need to create n number of objects in another model with default values.

I have a model called Room and it contains a field called number_of_beds based on that field we need to create n number of objects in anothe model called Bed.

Room(models.Model):
  room_no = IntegerField(primary_key=True,unique=True)
  number_of_beds = IntegerField()
  '''
  and so on
  '''

Bed(models.Model):
 room_no = models.ForeignKey('Room', on_delete=models.SET_NULL, null=True)
 bed_no = models.IntegerField(blank=True,default='Increment value')
 '''
 and so on
 '''

if number_of_beds =2, need to create two objects in Bed with default values under the same ForeignKey.

Any help would be appreciated.

1
  • 1
    what should be after update the number_of_beds? to large or to small number Commented May 8, 2019 at 13:02

1 Answer 1

1

simple solution is override the save

Room(models.Model):
  room_no = IntegerField(primary_key=True,unique=True)
  number_of_beds = IntegerField()

  def save(self, *args, **kwargs):
      super().save(*args, **kwargs)
      if self.number_of_beds > 0:
          for num in range(1, self.number_of_beds + 1):
              Bed.objects.get_or_create(room_no=self, bed_no=num)
      # clean extra beds
      self.bed_set.filter(bed_no__gt=self.number_of_beds).delete()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.