views:

120

answers:

3

For example, I have a model Posts and Comments.

Post.objects.annotate(Count('comment'))

I am making such query to get count of comments for every post. But in template i should check if this value greater than 4. As I know there is no such templatetag. For now I put method in model that executes comparision operation.

The question is, how to put field to model as annotate do?

A: 

Models are just classes, and in Python class instances are dynamic. This means you can add any property you like to an instance by simply assigning it.

myinstance = MyModel.objects.get(pk=1)
myinstance.mycomparisonattribute = True

However I don't see why this is any better than using your comparison method. Alternatively, use a custom template tag that can do comparisons - SmileyChris's smart if tag is excellent.

Daniel Roseman
You right, I understood my mistake. I write instead myinstance.mycomparisonattribute - myinstance['mycomparisonattribute']
dynback.com
A: 

You can try do it using custom Manager Probably, you should try to create custom Manager with overridden get_query_set() method, as described here

zzr
A: 

There are several ways you can add and extra attribute to a class. If its an attribute which can be calculated only once and used as a read-only from then onwards, I suggest using the property decorator.

For example:

@property
def foo(self):
    bar = do_some_calculation()
    return bar

But this will not be feasible for cases where you want to check the count of a certain type of object, because it will be changing over time.

Manager functions should be used to return a set of objects. If you want to return a boolean value indicating the whether a post has more than 4 comments, you can add a function to the model:

def more_than_4_replies(self):
   return self.objects.count() > 4

And you can also use aggregation to annotate the object set you pass into template and use an enhanced if tag like smart-if or pyif.

tarequeh