Skip to main content
 首页 » 编程设计

python之我在哪里放置一个函数来计算 Django 中的外键

2024年11月01日34JustinYoung

我有一个 Django 模型对象 Record,它具有指向另外两个模型 RecordType 和 Source 的外键:

class Record(models.Model): 
    title = models.CharField(max_length=200) 
    record_type = models.ForeignKey(RecordType) 
    source = models.ForeignKey(Source) 

问题:如果我想计算引用 ID 为“x”的 RecordType 和 ID 为“y”的 Source 的 Record 对象的数量,放置该函数的适当代码区域在哪里?

现在我在 views.py 中有它,我觉得这违反了“胖模型,瘦 View ”的最佳实践,所以我想将它从 views.py 中移走。但我不完全确定这是基于行还是基于表的操作类型,所以我不确定它是否应该作为模型方法实现,还是作为管理器实现。

这是 views.py 中的当前(工作)逻辑:

record_count = Record.objects.filter(record_type__id=record_type_.id, source__id=source_.id).count() 

需要说明的是,这不是如何获得计数的问题,而是将函数放置在代码的哪个区域的问题。

这是一个类似的问题,但它是在解决“如何”而不是“在哪里”: Counting and summing values of records, filtered by a dictionary of foreign keys in Django

请您参考如下方法:

如果结果涉及多行,则为表相关方法,按照Django约定,应为管理器方法。

来自 the Django docs :

Adding extra Manager methods is the preferred way to add “table-level” functionality to your models. (For “row-level” functionality – i.e., functions that act on a single instance of a model object – use Model methods, not custom Manager methods.)