Django: check for generic type in template?
I'm using generic types in my Profile
model:
user_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
details = generic.GenericForeignKey('user_type', 'object_id')
But now I want to check if a user is a certain type from within my template. I can get the user type with {{ user.get_profile.user_type }}
but t开发者_如何学编程hen what? Or how would I add a method to the model like is_type_xxx
so that I could use it in the template?
Maybe I don't fully understand the question, but it seems you can just define a function in your model that returns true if the type is what you need, then you can call that function from the template just as you would if you were accessing a variable.
In the model...
user_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
details = generic.GenericForeignKey('user_type', 'object_id')
def IsTypeX():
return user_type == x
In the template...
{% if user.get_profile.IsTypeX %}
{% endif %}
user_type
is a ForeignKey
to a ContentType
model, so treat it as you would any relation.
Although Ignacio is basically correct, I find that there can be a really tendency to get a lot of unintended DB hits if you're not careful. Since the number of ContentTypes
tends to be small and relatively unchanging, I cache a dict of name/id pairs to avoid it. You can use a signal to update your dict on the off chance a new ContentType is created.
You can then auto-create the necessary is_type_xxx()
functions/methods as needed. It's a little klunky, but the code isn't very complicated.
精彩评论