簡體   English   中英

通過 Django Admin 添加新產品時如何生成隨機 product_id int 到 MySQL

[英]How to generate a random product_id int to MySQL when adding a new product via Django Admin

我正在嘗試將“product_id”與新產品一起添加到 MySQL 數據庫中,以便在運行 Django 的電子商務網站中使用。然后我想使用這些 product_id 值在電子商務網站內進行搜索。 因此,它們只需要 5 個字符長。

models.py 中的產品 class 如下所示:

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()

據我了解,我應該能夠設置 integer 的長度,並將其設置為數字 ID,以便在每次在數據庫中創建新產品時存儲。

如果這個問題很愚蠢,我深表歉意,但這是我在這里的第一個問題,我進行了搜索但找不到解決方案。

值得一提的是,您正在將int類型傳遞給string方法。 這就是錯誤所指示的。

使用randint將返回 integer 並且最適合此用例。 一種方法是重寫 model 保存方法:

from random import randint

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(null=True, Blank=True)  # Max length 5, numerals only
    description = models.TextField(blank=True, null=True)
    price = models.FloatField()

    def save(self, **kwargs):
        if not self.product_id:
            self.product_id = randint(10000, 99999)
        return super(Product, self).save(**kwargs)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM