[英]How do I model a registration system with the following relationship constraints in Django?
I am trying to create a hackathon management system web application using Django.我正在尝试使用 Django 创建一个黑客马拉松管理系统 web 应用程序。 Each hackathon can have as many participating universities as possible (No constraints here).Now, each participating university can have at most 3 teams and each team can have at most 4 persons (1-4).
每个hackathon可以有尽可能多的参与大学(这里没有限制)。现在,每个参与的大学最多可以有3个团队,每个团队最多可以有4个人(1-4)。 I'm new to Django so help would be much appreciated.
我是 Django 的新手,非常感谢您的帮助。
from django.db import models
class Hackathon(models.Model):
name = models.CharField(max_length=50,blank=True,default='')
eventId = models.CharField(max_length=50, blank=True, default='')
startDate = models.DateField(null=True)
endDate = models.DateField(null=True)
location = models.TextField(max_length=100, blank=True, default='')
description = models.TextField(max_length=800, blank=True, default='')
#participants = models.ManyToManyField(...)??
def __str__(self):
return self.name
class University(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Team(models.Model):
team_name = models.CharField(max_length=50)
member_count = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(4)])
uni = models.ForeignKey(University, on_delete = models.CASCADE)
def __str__(self):
return self.team_name
class Person(models.Model):
name = models.CharField(max_length=50)
belongs_to = models.ForeignKey(Team,on_delete = models.CASCADE)
Your relational schema seems right for the use-case you describe.您的关系模式似乎适合您描述的用例。
The constraints you describe ( at most 3 teams and each team can have at most 4 persons ) are not really DB constraints but rather application constraints .您描述的约束(最多 3 个团队,每个团队最多可以有 4 人)不是真正的数据库约束,而是应用程序约束。 You will probably have to define a validation logic in overriding your Models
save()
method.您可能必须在覆盖您的模型
save()
方法时定义验证逻辑。
class Team(models.Model):
def save(self, *args, **kwargs):
if self.uni.teams.count() >= 3:
raise ValidationError("This university already has its 3 teams")
super().save(*args, **kwargs)
class Person(models.Model):
def save(self, *args, **kwargs):
if self.team.persons.count() >= 4:
raise ValidationError("This team already has its 4 people")
super().save(*args, **kwargs)
Also, I would recommend you to use Django 'User' model , which comes with several utils: password management, username unicity, ...etc.另外,我建议您使用Django 'User' model ,它带有几个实用程序:密码管理、用户名唯一性等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.