简体   繁体   English

如何将属性添加到 python class 中的实例变量

[英]How to add attribute to instance variables in a python class

To keep this simple, in my Django/Python sports pool application, each user is creating their own pool.为了简单起见,在我的 Django/Python 运动台球应用程序中,每个用户都在创建自己的台球池。 Therefore, in the Pool class, I need to make all the class variables be instance variables so no user is changing values on another users Pool class instance.因此,在池 class 中,我需要将所有 class 变量设为实例变量,因此没有用户更改其他用户池 class 实例的值。

A quick sample of code in the models.py file would be: models.py 文件中的代码示例如下:

  class Pool(models.Model):
     def __init__(self, team_name):
         self.team_name = team_name

What if I wanted to add attributes to the team_name field such as max_length = 100 or unique=True如果我想向 team_name 字段添加属性,例如max_length = 100unique=True

I understand the instance variables values must be passed to the class upon instantiation, so is it that the value being passed must already be defined with those attributes?我知道实例变量值必须在实例化时传递给 class,那么传递的值是否必须已经用这些属性定义? How do I handle this.我该如何处理。 Thanks!谢谢!

ps My apologies if I screwed up the formatting of this question. ps 如果我搞砸了这个问题的格式,我深表歉意。 I'm having challenges with inserting code.我在插入代码时遇到了挑战。 Sorry!对不起!

You can just add it into the field, for example:您可以将其添加到字段中,例如:

class Pool(models.Model): 
    team_name = models.CharField(max_length=100, unique=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

And so on.等等。 You can refer to the documentation: https://docs.djangoproject.com/en/3.0/ref/models/fields/可以参考文档: https://docs.djangoproject.com/en/3.0/ref/models/fields/

Adding a unique constraint: https://docs.djangoproject.com/en/3.0/ref/models/constraints/#uniqueconstraint添加唯一约束: https://docs.djangoproject.com/en/3.0/ref/models/constraints/#uniqueconstraint

If I understand what you are saying, you don't have to pass the variables on instantiation if the fields are blank=True and null=True .如果我理解您在说什么,如果字段为blank=Truenull=True ,则不必在实例化时传递变量。 You can then override the save() method to make sure they are there before committing to the database.然后,您可以覆盖save()方法以确保它们在提交到数据库之前就在那里。

For instance in models.py:例如在 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) 

In your views.py:在你的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM