【问题标题】:Get models.ManyToManyField selected options count获取 models.ManyToManyField 选择的选项计数
【发布时间】:2014-03-27 14:30:13
【问题描述】:

我不知道如何获取 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',但是如何?

【问题讨论】:

    标签: django django-models django-orm


    【解决方案1】:

    这可能是一种更简单的方法:

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

    【讨论】:

    • 是的,但这是一样的......但我想保存 authorsnumber 变量。并且 .authors.count() 不起作用
    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2011-09-22
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多