我需要訪問對象列表的外鍵,但我無法使其工作。Django - 在模板中訪問ForeignKey,但使用過濾器
這是我的模型
class Subcategory(models.Model):
# Relations
# Attributes - Mandatory
name = models.CharField(
max_length=50,
verbose_name=_('name'),
)
class Product(models.Model):
# Attributes - Mandatory
name = models.CharField(
max_length=63,
unique=True,
verbose_name=_('name'),
)
slug = models.SlugField(
max_length=63,
unique=True,
editable=False,
verbose_name=_('slug'),
)
title = models.CharField(
max_length=63,
editable=False,
help_text=_('name to show the product in the templates'),
verbose_name=_('title')
)
subcategory = models.ForeignKey(
Subcategory,
verbose_name=_('subcategory'),
)
# Precio de venta al público
sell_price = models.DecimalField(
max_digits=10,
decimal_places=2,
verbose_name=_('sell price'),
)
minimal_quantity = models.SmallIntegerField(
default=1,
verbose_name=_('minimal quantity'),
)
available = models.BooleanField(
default=True,
)
created = models.DateTimeField(
editable=False,
verbose_name=_('created'),
)
modified = models.DateTimeField(
editable=False,
verbose_name=_('modified'),
)
,我要訪問該股票的產品
class ProductStock(models.Model):
# Relations
product = models.ForeignKey(
Product,
verbose_name=_('product'),
)
warehouse = models.ForeignKey(
Warehouse,
default = 1,
verbose_name=_('warehouse'),
)
# Attributes - Mandatory
quantity = models.IntegerField(
verbose_name=_('quantity'),
)
這是倉庫模型,它在其他應用程序
class Warehouse(models.Model):
# Relations
store = models.ForeignKey(
Store,
blank=True,
null=True,
related_name='warehouse',
verbose_name=_('store'),
)
# Attributes - Mandatory
name = models.CharField(
max_length=50,
verbose_name=_('name'),
)
# Attributes - Optional
address = models.CharField(
max_length=100,
verbose_name=_('address'),
)
phone = models.CharField(
max_length=50,
verbose_name=_('phone'),
)
# Attributes - Optional
phone2 = models.CharField(
max_length=50,
blank=True,
null=True,
verbose_name=_('phone 2'),
)
mail = models.EmailField(
verbose_name=_('mail'),
)
這是我的功能視圖
def product_stock_list(request, subcategory_id=None):
subcategory = None
subcategories = Subcategory.objects.all().order_by('family', 'name')
products = Product.objects.filter(available=True).exclude(subcategory=1)
if subcategory_id:
subcategory = get_object_or_404(Subcategory, id=subcategory_id)
products = products.filter(subcategory=subcategory)
if request.GET:
try:
ean13 = request.GET.get('ean13')
ean13 = ean13.upper()
p = products.get(ean13=ean13)
return redirect(reverse('products:detail', kwargs=({'id': p.id, 'slug': p.slug})))
except:
products = None
return render(
request,
'products/stock_list.html',
{
'subcategory': subcategory,
'subcategories': subcategories,
'products': products,
}
)
那麼,我試圖得到的列表產品的數量是ID = 1的倉庫上的產品數量。
我需要的正是這樣: Produc1 - 數量 產品2 - 數量 產品3 - 數量 ... ... ProductN - 數量
感謝您的幫助!
提供您的倉庫模型! – shuboy2014
已經添加到帖子中!謝謝 – marcosgue