Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python/Django—使用某个对象作为外键的其他对象的计数_Python_Django_Sqlite - Fatal编程技术网

Python/Django—使用某个对象作为外键的其他对象的计数

Python/Django—使用某个对象作为外键的其他对象的计数,python,django,sqlite,Python,Django,Sqlite,我正在开发一个测试Django应用程序CatDB。我希望每个“所有者”类都有一个变量,即将该所有者列为其所有者的猫的数量 在my Models.py中: 从django.db导入模型 class Owner(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() location = models.CharField(max_length=50) def _

我正在开发一个测试Django应用程序CatDB。我希望每个“所有者”类都有一个变量,即将该所有者列为其所有者的猫的数量

在my Models.py中: 从django.db导入模型

class Owner(models.Model):
    name = models.CharField(max_length=50)
    age = models.IntegerField()
    location = models.CharField(max_length=50)
    def __str__(self):
        return self.name
    def num_cats(self): //This is the line in question
        return cat_set.count()

class Cat(models.Model):
    name = models.CharField(max_length=50)
    owner = models.ForeignKey(Owner)
    age = models.IntegerField()
    color = models.CharField(max_length=30)
    def __str__(self):
        return self.name
我试图用一个名为num_cats的变量来实现这一点,但它不起作用

另外,在my Admin.py中:

from django.contrib import admin
from catdb.models import Cat, Owner


class OwnerAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Basic information', {'fields': ['name','location'], 'classes': ['collapse']}),
    ]
    list_display = ('name','location','num_cats') //Use num_cats as a column in the list


admin.site.register(Owner, OwnerAdmin)
admin.site.register(Cat)

如何正确实现此功能?

而不是
cat\u set.count()
您需要
self.cat\u set.count()
,因此它应该是:

def num_cats(self):
    return self.cat_set.count()