这是我对如何实现这一目标的最初想法:
products = Product.objects.all()
for product in products:
if product in cart:
products = Product.objects.exclude(product)
我的两个问题是: 1.)这是否有效/有意义? 2.)我将把哪个.py文件放进去?
from django.shortcuts import render
from django.shortcuts import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Dropoff, DropoffItem
from products.models import Product
from .forms import AddDropoffItemForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.decorators import login_required
def add_item_dropoff_order(request):
request.session.set_expiry(120000)
try:
user = request.user
the_id = request.session['dropoff_id']
dropoff = Dropoff.objects.get(id=the_id)
except:
user = request.user
new_dropoff_order = Dropoff(user=user)
new_dropoff_order.save()
request.session['dropoff_id'] = new_dropoff_order.id
the_id = new_dropoff_order.id
dropoff = Dropoff.objects.get(id=the_id)
try:
product = Product.objects.get(sku=sku)
except Product.DoesNotExist:
pass
except:
pass
form = AddDropoffItemForm(request.POST or None)
if request.method == "POST":
product_sku = str(request.POST['product'])
dropoff_item = DropoffItem.objects.create(dropoff=dropoff, product_id=product_sku)
dropoff_item.save()
return HttpResponseRedirect('%s'%(reverse('add_item_dropoff_order')))
context = {
"dropoff": dropoff,
"form": form,
}
return render(request, 'dropoffs/add_item_dropoff_order.html', context)
from django import forms
from .models import Dropoff, DropoffItem
from products.models import Product
class AddDropoffItemForm(forms.ModelForm):
product = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = DropoffItem
fields = ["product"]
基本上,一旦dropoff_item.save()发生,我想从forms.py文件中调用的查询集中删除该产品。
是否可以在视图中重新定义查询集,然后在forms.py中再次调用它?
答案 0 :(得分:0)
不,不是真的:)我会这样做:
products = Product.objects.exclude(id__in=cart.product_ids)
如果没有看到你的应用程序逻辑,就不可能告诉你在哪里放这些代码,但是既然你已经标记了django视图,我假设你想要它在视图中。