python - 如何在django中保存多对多关系

标签 python django

How to create an object for a Django model with a many to many field?

从上面的问题我知道我们只能在以后保存多对多字段。

模型.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()

文件上传工作正常然后我修改我的代码以添加商店然后我在这里......

现在我确定数据库返回 ID 在这里。然后我尝试使用下面的代码,但这只给我错误

    x = new_track.id
    new = Foo.objects.filter(id=x)
    new.store.id = request.POST['store']
    new.save()

好的,所以这里的错误是'QuerySet' object has no attribute 'store'

而且我还尝试使用 add 现在可以正常工作了。 所以问题是如何保存()

最佳答案

保存具有多对多关系的对象的正确方法是:

...
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)

关于python - 如何在django中保存多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26063189/

相关文章:

python - 仅从 BeautifulSoup 获取数字而不是整个 div

mysql - 新的 mysql 数据库出现 "mydb.background_task doesn' t 存在”- Django

python - Django - Apache : get extended key usage field from x509 client certificate

javascript - Django urlpatterns 正则表达式不精确,得到 404?

django - DRF PrimaryRelatedField 写入时和 NestedSerializer 读取时?

python - 逐行打印字典的元素

python - 在 Python 中创建两个具有相同值的不可变对象(immutable对象)

python - 从列表格式的数据框列中删除重复项

python - 未授予 Google Drive API 读取权限

django - South 的 add_introspection_rules() 有 Django 1.7+ 的替代品吗?