我正在尝试使用4种型号制作库存系统 - 类别,产品组,产品,库存 - 如下所示。
class Category(MPTTModel):
name=models.CharField(max_length=75,null=False,blank=False, unique=True)
parent=TreeForeignKey('self', null=True, blank=True, related_name='children')
class ProductGroup(models.Model):
name = models.CharField(max_length=30,null=False, blank=False)
category=TreeForeignKey('category.Category', null=False,blank=False)
class Product(models.Model):
product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False)
manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False)
product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE,)
opening_stock=models.PositiveIntegerField(default=0)
TRANSACTION_TYPE=(('I','Stock In'),('O','Stock Out'))
class Stock(models.Model):
product=models.ForeignKey('product.Product', blank=False,null=False)
quantity=models.PositiveIntegerField(blank=False, null=False)
ttype=models.CharField(max_length=1,verbose_name="Transaction type",choices=TRANSACTION_TYPE, blank=False)
我有一个用于记录Stock-In / Out的模型表格如下。
class StockInOutForm(forms.ModelForm):
class Meta:
model = Stock
fields=['product','quantity','date']
(以及StockIn和StockOut的两个单独视图设置 ttype )
由于表产品基本上是ProductGroup,Manufacturer和ProductType的排列,因此它将包含大量记录。
我需要将Cateogry和ProductGroup字段添加为链接字段,以便表单中的for Product.name只包含一个过滤集。
请提供一些有关如何进行的见解。
感谢。
答案 0 :(得分:0)
谢谢@Exprator 为了按所需顺序获取字段,我使用了以下代码。
from collections import OrderedDict
class StockInOutForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user','')
super(StockInOutForm, self).__init__(*args, **kwargs)
self.fields['category']=TreeNodeChoiceField(queryset=Category.objects.all())
self.fields['product_group']=forms.ModelChoiceField(queryset=ProductGroup.objects.filter(id=0))
self.fields['product']=forms.ModelChoiceField(queryset=ProductGroup.objects.filter(id=0))
original_fields = self.fields
new_order = OrderedDict()
for key in ['category','product_group', 'product','quantity','date']:
new_order[key] = original_fields[key]
self.fields = new_order