3

我想检查一下我在多字段上设置的关系不超过 3 个。

我尝试了干净的方法来做到这一点:

if self.tags.count()>3:
  raise ValidationError(_(u'You cannot add more than 3 tags'))

self.tags不返回当前更新......只返回保存的对象。

您有访问它们的想法吗?

谢谢

4

2 回答 2

3

You could do this a couple of ways.

First, you could do it as part of the model's save()

In your model, do something like this:

def save(self):
  # this may not be the correct check... but it will be something like this
  if self.tags.count() > 3: 
    # raise errors here
  else:
    super(MODEL_NAME,self).save()

Or you could do it manually in the view.

def some_view(request):

  # all the request.POST checking goes here

  the_model = form.save(commit=False)
  if the_model.tags.count() > 3:
    #error stuff
  else:
    the_model.save()
于 2010-04-27T16:16:47.347 回答
-2

布兰特是正确的。但是,我认为做你想做的更好的方法是使用三个单独的 ForeignKey 字段而不是一个 ManyToMany。

于 2010-05-14T00:44:54.453 回答