在django中如何处理未保存的多对多关系? [英] How to work with unsaved many-to-many relations in django?

查看:91
本文介绍了在django中如何处理未保存的多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在django有几个模型,它们连接多对多。我想在内存中创建这些模型的实例,将它们呈现给用户(通过视图模板中的自定义方法调用),如果用户满意,将它们保存到数据库。 p>

但是,如果我尝试对模型实例(调用渲染方法,例如)执行任何操作,我会收到一条错误消息,表示我必须先保存实例。文档说,这是因为模型是多对多的关系。



如何将对象呈现给用户并允许他/她保存或丢弃它们而不会使我的数据库混乱?



(我想我可以关闭事务处理,并在整个项目中自己做,但这听起来像是一个潜在的错误测量...)



Thx!

解决方案

我认为使用django表单可能是答案,如文档中所述(搜索m2m ...)。



编辑为其他可能有同样问题的人添加一些解释:



说你有一个这样的模型:

 从django.db导入模型
从django.forms import ModelForm

class Foo(models.Model):
name = models.CharField(max_le ngth = 30)

class Bar(models.Model):
foos = models.ManyToManyField(Foo)

def __unicode __(self):
返回.join([x.name for x in foos])

那么你不能调用unicode ()在未保存的Bar对象上。如果你想在保存之前打印出来,你必须这么做:

  class BarForm(ModelForm): 
class Meta:
model = Bar

def example():
f1 = Foo(name ='sue')
f1.save()
f2 = foo(name ='wendy')
f2.save()
bf = BarForm({'foos':[f1.id,f2.id]})
b = bf.save(commit = false)
#不幸的是,unicode(b)在正确保存之前不起作用,
#所以我们需要这样做:
if (不是bf.is_valid()):
打印bf.errors
其他:
在bf.cleaned_data.items()中的(键,值):
打印键+ =>+ str(value)

所以,在这种情况下,你必须保存Foo对象(您可以在保存这些对象之前使用自己的表单进行验证),并在使用多个密钥保存模型之前,还可以验证这些对象。所有这些都不需要保存数据太早,搞乱数据库或处理交易...


I have a couple of models in django which are connected many-to-many. I want to create instances of these models in memory, present them to the user (via custom method-calls inside the view-templates) and if the user is satisfied, save them to the database.

However, if I try to do anything on the model-instances (call rendering methods, e.g.), I get an error message that says that I have to save the instances first. The documentation says that this is because the models are in a many-to-many relationship.

How do I present objects to the user and allowing him/her to save or discard them without cluttering my database?

(I guess I could turn off transactions-handling and do them myself throughout the whole project, but this sounds like a potentially error-prone measure...)

Thx!

解决方案

I think that using django forms may be the answer, as outlined in this documentation (search for m2m...).

Edited to add some explanation for other people who might have the same problem:

say you have a model like this:

from django.db import models
from django.forms import ModelForm

class Foo(models.Model):
    name = models.CharField(max_length = 30)

class Bar(models.Model):
      foos = models.ManyToManyField(Foo)

  def __unicode__(self):
      return " ".join([x.name for x in foos])

then you cannot call unicode() on an unsaved Bar object. If you do want to print things out before they will be saved, you have to do this:

class BarForm(ModelForm):
    class Meta:
        model = Bar

def example():      
    f1 = Foo(name = 'sue')
    f1.save()
    f2 = foo(name = 'wendy')
    f2.save()
    bf = BarForm({'foos' : [f1.id, f2.id]})
    b = bf.save(commit = false)
    # unfortunately, unicode(b) doesn't work before it is saved properly,
    # so we need to do it this way: 
    if(not bf.is_valid()):
        print bf.errors
    else:
        for (key, value) in bf.cleaned_data.items():
            print key + " => " + str(value)

So, in this case, you have to have saved Foo objects (which you might validate before saving those, using their own form), and before saving the models with many to many keys, you can validate those as well. All without the need to save data too early and mess up the database or dealing with transactions...

这篇关于在django中如何处理未保存的多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆