这是我的models.py
from django.db import models
from item.models import Item
from django.contrib.auth.models import User
class Catalog(models.Model):
title = models.CharField(max_length=200)
item = models.ManyToManyField(Item, blank=True, null=True)
user = models.ForeignKey(User)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.title
这是我的views.py
def catalog(request):
# if this is a POST request we need to process the form data
qs = Item.objects.filter(user = request.user)
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = catalogForm(qs,request.POST)
# check whether it's valid:
if form.is_valid():
title=form.cleaned_data['title']
item=form.cleaned_data['item']
user= request.user
q = Catalog(title=title, pub_date=timezone.now(),user=user)
q.save()
q.item = item.values()
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = catalogForm(qs)
return render(request, 'catalog/catalog.html', {'form': form})
现在item = models.ManyToManyField(Item, blank=True, null=True)
创建2个表catalog_catalog
和catalog_catalog_item
。使用q.save()
,我可以将数据插入到单个表catalog_catalog
中,但我无法将数据插入catalog_catalog_item
。
我在这里缺少什么。感谢您的帮助。
答案 0 :(得分:0)
add()接受任意数量的参数,而不是它们的列表。
float
要将该列表扩展为参数,请使用add(obj1, obj2, obj3, ...)
*
将其用作评论中提到的(@EchoUA团队)
add(*[obj1, obj2, obj3])
答案 1 :(得分:0)
您缺少第二次“save()”调用。
q = Catalog(title=title, pub_date=timezone.now(),user=user)
q.save()
q.item = item.values()
q.save() # you need this save as well