我无法弄清楚如何获得manytomanyfield选择的选项号
我的代码:
class Author(models.Model):
first_name = models.CharField(max_length=30)
def __unicode__(self):
return u'%s' % (self.first_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
authorsnumbers = models.IntegerField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if not self.id:
self.authorsnumbers = self.authors.count()
super(Event, self).save(*args, **kwargs)
如果我选择2位作者,我希望authorsnumber为“2”,但是如何?
答案 0 :(得分:0)
这可能是一种更简单的方法:
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
def authorsnumbers(self):
return self.authors.count()
def __unicode__(self):
return self.title
当然,您可以在任何需要的地方使用book.authors.count()
代替book.authorsnumber()
。