获取models.ManyToManyField选择的选项计数

时间:2014-03-27 14:30:13

标签: django django-models django-orm

我无法弄清楚如何获得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”,但是如何?

1 个答案:

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