通过 Django Admin 添加新产品时如何生成随机的product_id int

我正在尝试将“product_id”与新产品一起添加到 MySQL 数据库,以便在运行 Django 的电子商务网站中使用。然后,我想使用这些 Product_id 值在电子商务网站内进行搜索。因此,它们的长度只需 5 个字符。


models.py 中的产品类如下所示:


from django.utils.crypto import get_random_string


class Product(models.Model):

    title = models.CharField(max_length=255)

    slug = models.SlugField(max_length=255)

    category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)

    product_id = models.IntegerField(get_random_string(5, 1234567890))  # Max length 5, numerals only

    description = models.TextField(blank=True, null=True)

    price = models.FloatField()

当尝试将模型迁移到 MySQL 服务器时,我得到:


File "C:\Users\user\Desktop\ecommerce\apps\store\models.py", line 18, in <module>

   class Product(models.Model):

 File "C:\Users\user\Desktop\ecommerce\apps\store\models.py", line 22, in Product

   product_id = models.IntegerField(get_random_string(5, 1234567890))  # Create a random numeric id for each product

 File "C:\Users\user\Desktop\ecommerce\venv\lib\site-packages\django\utils\crypto.py", line 74, in get_random_string

   return ''.join(secrets.choice(allowed_chars) for i in range(length))

 File "C:\Users\user\Desktop\ecommerce\venv\lib\site-packages\django\utils\crypto.py", line 74, in <genexpr>

   return ''.join(secrets.choice(allowed_chars) for i in range(length))

 File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\random.py", line 288, in choice

   i = self._randbelow(len(seq))

TypeError: object of type 'int' has no len()

据我了解,我应该能够设置整数的长度,并将其设置为每次在数据库中创建新产品时存储的数字 ID。


如果这个问题很愚蠢,我很抱歉,但这是我的第一个问题,我进行了搜索,但找不到解决方案。


www说
浏览 89回答 1
1回答

蛊毒传说

值得一提的是,您正在将int类型传递给string方法。这就是错误所指示的内容。使用randint将返回一个整数,最适合此用例。一种方法是重写模型保存方法:from random import randintclass Product(models.Model):&nbsp; &nbsp; title = models.CharField(max_length=255)&nbsp; &nbsp; slug = models.SlugField(max_length=255)&nbsp; &nbsp; category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)&nbsp; &nbsp; product_id = models.IntegerField(null=True, Blank=True)&nbsp; # Max length 5, numerals only&nbsp; &nbsp; description = models.TextField(blank=True, null=True)&nbsp; &nbsp; price = models.FloatField()&nbsp; &nbsp; def save(self, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; if not self.product_id:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.product_id = randint(10000, 99999)&nbsp; &nbsp; &nbsp; &nbsp; return super(Product, self).save(**kwargs)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python