如何在django中保存多对多的关系 [英] how to save Many to Many relationship in django
问题描述
从上面的问题我知道我们可以保存多对多字段后来只有。
From above question i come to know we can save Many to Many field later only.
models.py
class Store(models.Model):
name = models.CharField(max_length=100)
class Foo(models.Model):
file = models.FileField(upload_to='')
store = models.ManyToManyField(Store, null=True, blank=True)
views.py
new_track.file = request.FILES['file']
new_track.save()
文件上传工作正常,然后我修改我的代码添加商店,然后我在这里...
And file uploading working fine then later i modify my code to add store then i am here...
现在我确定db return id在这里。然后我尝试使用我的下面的代码,但这只给我错误
Now i am sure db return id's here. Then i tried with my below code but that's given me error only
x = new_track.id
new = Foo.objects.filter(id=x)
new.store.id = request.POST['store']
new.save()
好,所以这里的错误是'QuerySet'对象没有属性'store'
ok so the error here is 'QuerySet' object has no attribute 'store'
而且我也尝试使用 add
,这也正在工作。
所以问题是如何保存()
And also i tried with add
that's now working either.
So the question is how to save()
推荐答案
使用manytomany关系保存对象的正确方法是:
the right way of saving objects with manytomany relations would be:
...
new_track.file = request.FILES['file']
new_track.save()
new_store = Store.objects.get(id=int(request.POST['store']))
new_track.store.add(new_store)
这篇关于如何在django中保存多对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!