Issue
I have a model caled BookTable and a model Table, i want users to be able to book for the same table but not at the same time but i have no clue how am i going to make it.
My BookingTable model...
class BookingTable(models.Model):
TIME_CHOICES =[
('08:00', '08:00'),
('09:00', '09:00'),
('10:00', '10:00'),
('11:00', '11:00'),
('12:00', '12:00'),
('13:00', '13:00'),
('14:00', '14:00'),
('15:00', '15:00'),
('16:00', '16:00'),
('17:00', '17:00'),
('18:00', '18:00'),
('19:00', '19:00'),
('20:00', '20:00'),
('21:00', '21:00'),
]
table = models.ForeignKey(Table, on_delete=models.CASCADE)
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
time = models.TimeField(default='00:00', choices=TIME_CHOICES)
def get_absolute_url(self):
return reverse("list_tables")
def __str__(self) -> str:
return self.user.username + "-" + self.table.name
My Table model...
class Table(models.Model):
name = models.CharField(max_length=100, unique=True)
size = models.PositiveIntegerField()
image = models.ImageField(upload_to='static/media/images/', default='static/media/images/default.jfif')
description = models.TextField(null=False, blank=False, default="This is a very beatiful table")
def __str__(self) -> str:
return self.name[:50]
def get_absolute_url(self):
return reverse("list_tables")
I don't know where to start from
Solution
You can add a constraint to you model; as follows:
class BookingTable(models.Model):
...
class Meta:
constraints = [
models.UniqueConstraint(fields=['table', 'time'], name='unique_username_email')
]
For this kind of issue costraints and validators are almost always the solution. You can learn more about constraints here: https://docs.djangoproject.com/en/5.0/ref/models/constraints/
And more about validators here: https://docs.djangoproject.com/en/5.0/ref/validators/
Answered By - 42WaysToAnswerThat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.