开发者

How to limit manytomanyfields on a model?

I would like to check that I get not more than 3 relations set on a manytomanyfield.

I tried on the clean method to do this :

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

But self.tags 开发者_JAVA百科returns not the current updates... only saved objects.

Do you have an idea to access to them ?

Thanks


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


Brant is correct. However, I think a better way to do what you want is to use three individual ForeignKey fields instead of one ManyToMany.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜