当我运行 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 字段导致错误,甚至在创建表之前查询就在运行。
p_name = forms.ChoiceField(label='Select Product',choices=list ((obj.product_code,obj.name) for obj in Product.objects.all()))
我怎样才能摆脱这种情况并解决错误!