django.db.utils.OperationalError: no such table: store_product

django.db.utils.OperationalError: no such table: store_product

当我运行 makemigrations 发生错误。 这里是models.py

def unique_order_id():
    not_unique = True
    while not_unique:
        uo_id = random.randint(1000000000, 9999999999)
        if not Order.objects.filter(order_id=uo_id):
            not_unique = False
    return uo_id


class Product(models.Model):
    #product code, name, category, unit price, current stock
    product_code = models.IntegerField(unique=True)
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=100)
    unit_price = models.FloatField()
    current_stock = models.IntegerField()
    
    def __str__(self):
        return self.name


class Order(models.Model):
    
    order_id = models.IntegerField(unique=True, 
                        default=unique_order_id)
    customer_name =  models.CharField(max_length=100)
    phone = models.CharField(max_length=14)
    email = models.EmailField()

    qr_code = models.ImageField(upload_to='qr_codes', blank=True)

    
    def __str__(self):
        return self.customer_name

    #override ths save method for creating qrcode based on fields on this model.
    def save(self, *args, **kwargs):
        qr_info = "Invoice No : "+ str(self.order_id)+" Name : "+self.customer_name +" Phone : "+str(self.phone)+ " Email : "+ self.email
        qrcode_img = qrcode.make(qr_info)
        #canvas = Image.new('RGB', (290, 290), 'white')
        canvas = Image.new('RGB', (qrcode_img.pixel_size, qrcode_img.pixel_size), 'white')
        canvas.paste(qrcode_img)
        fname = f'qr_code-{self.customer_name}.png'
        buffer = BytesIO()
        canvas.save(buffer,'PNG')
        self.qr_code.save(fname, File(buffer), save=False)
        canvas.close()
        super().save(*args, **kwargs)

class OrderItem(models.Model):
    
    qty = models.IntegerField(default=0)

    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)

    #this will return total price of product(unit_price*quntity)
    @property
    def get_total(self):
        total = self.product.unit_price * self.qty
        return total

这是forms.py个代码

class ItemSelectForm(forms.Form):
    p_name = forms.ChoiceField(label='Select Product',choices=list ((obj.product_code,obj.name) for obj in Product.objects.all()))   
    qty = forms.IntegerField()

    #function for checking product avaiability
    def clean_qty(self):
        data = self.cleaned_data['qty']
        product_code = self.cleaned_data['p_name']
        product = Product.objects.get(product_code = product_code)
        if data > product.current_stock:
            raise forms.ValidationError(('Insufficient Stock'), code='ins_stock')
        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return data

此代码在我的环境中运行良好,但是当我 运行 在另一个环境中执行此代码并且 运行 makamigrations 时,会出现此错误。在线搜索后,我的理解是,表单中的 p_name 字段导致错误,甚至在创建 table.

之前,查询是 运行ning
p_name = forms.ChoiceField(label='Select Product',choices=list ((obj.product_code,obj.name) for obj in Product.objects.all()))

我怎样才能摆脱这种情况并解决错误!

ItemSelectForm 上的 p_name 字段初始化时,您正在执行查询,此初始化发生在您的应用程序为 parsed/loaded/started 时。在您的应用程序启动时执行查询是不好的做法,在这种情况下会阻止您 运行 迁移,因为您 运行 的查询是针对尚未迁移的模型。

改为使用 ModelChoiceField 并向其传递一个查询集,该查询集不会在启动时执行,应该可以缓解此问题

class ItemSelectForm(forms.Form):
    product = forms.ModelChoiceField(Product.objects.all(), label='Select Product')  
    qty = forms.IntegerField()

    #function for checking product availability
    def clean_qty(self):
        data = self.cleaned_data['qty']
        product = self.cleaned_data['product']
        if data > product.current_stock:
            raise forms.ValidationError(('Insufficient Stock'), code='ins_stock')
        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return data