我想在我的models.py中设置一个查询,以便可以通过管理视图以及模板来访问它。我遇到的问题是在admin.py和view.py中声明查询集。我想要一个查询集,我可以在任何地方访问它
这是我在admin.py中的代码
import numpy as np
a = [[1,1],[1,2],[1,3]]
a = np.array([[1,1],[1,2],[1,3]])
>>> a
array([[1, 1],
[1, 2],
[1, 3]])
dic = {3:2,2:3}
vfunc = np.vectorize(lambda x:dic[x] if x in dic else x)
a[:,1] = vfunc(a[:,1])
>>> a
array([[1, 1],
[1, 3],
[1, 2]])
这是我在views.py中的代码
def get_queryset(self, request):
qs = super(ItemTableAdmin, self).get_queryset(request)
qs = qs.annotate(
stock=(F('amount') - F('consumption'))
)
return qs
def stock(self, obj):
return obj.stock
在管理面板和模板中也给我相同的结果。 例如: 8.00-7.00 = 1.00
现在这是我在model.py中的代码,该代码将实现相同的目标并同时获得管理员和模板的访问权限
my_models = list(ItemTable.objects.all().annotate(stock=(F('amount') -
F('consumption'))))
my_models_table = items(my_models)
RequestConfig(request).configure(my_models_table)
我希望输出为8.00-7.00 = 1.00,但我得到的输出是:
from django.db.models import F
class ItemTable(models.Model):
refno = models.CharField("Reference No", max_length=50, unique=True, null=False)
slno = models.CharField("Serial No", max_length=50, null=False)
date = models.DateField("Entry Date")
mata_name = models.TextField("Name of Materials", blank=True)
manu_name = models.CharField("Manufacturer Name", max_length=50, blank=True)
batch_no = models.CharField("Batch No", max_length=50, blank=True)
product = models.TextField("Used in Product", blank=True)
agent = models.CharField("Local Agent", max_length=250, blank=True)
mfgdate = models.DateField("MFG Date", null=True, blank=True)
expdate = models.DateField("EXP Date", null=True, blank=True)
amount = models.DecimalField(max_digits=12, decimal_places=4, blank=True, null=True)
consumption = models.DecimalField(max_digits=12, decimal_places=4, blank=True, null=True)
coa = models.FileField("Certificate of Analysis", upload_to='pdf/coa', blank=True, null=True)
msds = models.FileField(upload_to='pdf/msds', blank=True, null=True)
moa = models.FileField("Method of Analysis", upload_to='pdf/moa', blank=True, null=True)
def query(self):
return ItemTable.objects.all().annotate(stock=F('amount') -
F('consumption'))