[英]How to add attribute to instance variables in a python class
为了简单起见,在我的 Django/Python 运动台球应用程序中,每个用户都在创建自己的台球池。 因此,在池 class 中,我需要将所有 class 变量设为实例变量,因此没有用户更改其他用户池 class 实例的值。
models.py 文件中的代码示例如下:
class Pool(models.Model):
def __init__(self, team_name):
self.team_name = team_name
如果我想向 team_name 字段添加属性,例如max_length = 100
或unique=True
我知道实例变量值必须在实例化时传递给 class,那么传递的值是否必须已经用这些属性定义? 我该如何处理。 谢谢!
ps 如果我搞砸了这个问题的格式,我深表歉意。 我在插入代码时遇到了挑战。 对不起!
您可以将其添加到字段中,例如:
class Pool(models.Model):
team_name = models.CharField(max_length=100, unique=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
等等。 可以参考文档: https://docs.djangoproject.com/en/3.0/ref/models/fields/
添加唯一约束: https://docs.djangoproject.com/en/3.0/ref/models/constraints/#uniqueconstraint
如果我理解您在说什么,如果字段为blank=True
和null=True
,则不必在实例化时传递变量。 然后,您可以覆盖save()
方法以确保它们在提交到数据库之前就在那里。
例如在 models.py 中:
class Pool(models.Model):
name = models.CharField(max_length=100, unique=True, blank=True, null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
def save(self, *args, **kwargs):
if self.name is None or self.user is None:
raise ValueError # or do something else or raise another error
else:
super(Pool, self).save(*args, **kwargs)
在你的views.py中:
def pools(request):
...
try:
user1_pool = Pool.objects.create()
user1_pool.name = "My Pool Name"
user1_pool.user = request.user
user1_pool.save()
except ValueError:
# do something, send a message to user, etc.
...
try:
user2_pool = Pool.objects.create()
user2_pool.name = "Another Pool Name"
user2_pool.user = some_other_user
user2_pool.save()
except ValueError:
# do something, send a message to user, etc.
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.