Sectio Aurea
Sectio Aurea

Reputation: 393

Where do I put a function to count foreign keys in Django?

I have a Django model object, Record, which has foreign keys to two other models RecordType and Source:

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

Question: If I want to count the number of Record objects which refer to RecordType with id "x" and Source with id "y", where is the appropriate area of code to put that function?

Right now I have it in views.py and I feel that is a violation of best practices for "fat model, thin views", so I want to move it from views.py. But I'm not entirely sure if this is a row-based or table-based type of operation, so I'm not sure if it should be implemented as a model method, or instead as a manager.

Here's the current (working) logic in views.py:

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

Just to be clear, this isn't a question of how to get the count, but simply in which area of code to put the function.

Here's a similar question, but which was addressing "how to" not "where": Counting and summing values of records, filtered by a dictionary of foreign keys in Django

Upvotes: 2

Views: 388

Answers (1)

If the result involves multiple rows, it is a table-related method, and according to Django conventions, should be a manager method.

From 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.)

Upvotes: 2

Related Questions