第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

通過 Django Admin 添加新產(chǎn)品時如何生成隨機的product_id int

通過 Django Admin 添加新產(chǎn)品時如何生成隨機的product_id int

www說 2023-12-29 16:42:39
我正在嘗試將“product_id”與新產(chǎn)品一起添加到 MySQL 數(shù)據(jù)庫,以便在運行 Django 的電子商務(wù)網(wǎng)站中使用。然后,我想使用這些 Product_id 值在電子商務(wù)網(wǎng)站內(nèi)進行搜索。因此,它們的長度只需 5 個字符。models.py 中的產(chǎn)品類如下所示: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()當(dāng)嘗試將模型遷移到 MySQL 服務(wù)器時,我得到: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()據(jù)我了解,我應(yīng)該能夠設(shè)置整數(shù)的長度,并將其設(shè)置為每次在數(shù)據(jù)庫中創(chuàng)建新產(chǎn)品時存儲的數(shù)字 ID。如果這個問題很愚蠢,我很抱歉,但這是我的第一個問題,我進行了搜索,但找不到解決方案。
查看完整描述

1 回答

?
蠱毒傳說

TA貢獻1895條經(jīng)驗 獲得超3個贊

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


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


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)


查看完整回答
反對 回復(fù) 2023-12-29
  • 1 回答
  • 0 關(guān)注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號