亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

www說 2023-12-29 16:42:39
我正在嘗試將“product_id”與新產品一起添加到 MySQL 數據庫,以便在運行 Django 的電子商務網站中使用。然后,我想使用這些 Product_id 值在電子商務網站內進行搜索。因此,它們的長度只需 5 個字符。models.py 中的產品類如下所示:from django.utils.crypto import get_random_stringclass 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。如果這個問題很愚蠢,我很抱歉,但這是我的第一個問題,我進行了搜索,但找不到解決方案。
查看完整描述

1 回答

?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

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


使用randint將返回一個整數,最適合此用例。一種方法是重寫模型保存方法:


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)


查看完整回答
反對 回復 2023-12-29
  • 1 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號