如何使用这些模型在Django中为用户模型添加is_client方法?

时间:2013-10-01 06:30:46

标签: django django-models django-templates

我有User,UserClient和Client模型,如下所示:

一个客户可以拥有多个用户:

  class Client(models.Model):

    user = models.OneToOneField(User)

    # Which company the client represents
    company = models.CharField(max_length=200, null=True)

    # Address of the company
    address = models.CharField(max_length=200, null=True)

    company_size = models.ForeignKey(CompanySize, null=True)

    account_type = models.ForeignKey(AccountType)

    billing_address = models.CharField(max_length=254, null=True)

    # Billing Information of the client

    def __unicode__(self):
        return self.user.username

class ClientUser(models.Model):

    user = models.OneToOneField(User)
    client = models.ForeignKey(Client)

    def __unicode__(self):
        return self.user.email

现在在模板中,我想这样做:

{% if user.is_client %}

{{ do_this }}

怎么做?

1 个答案:

答案 0 :(得分:1)

假设"用户"在您的模板中是django.contrib.auth.User个实例,向is_client()添加User方法的最简单方法是monkeypatch User

# youmodels.py
from django.contrib.auth.models import User

# your models here...

def user_is_client(user):
    try:
        client = user.client
    except Client.DoesNotExist:
        return False
    else:
        return True

User.is_client = user_is_client

但正如schneck评论的那样,如果您的django版本已经足够新,那么拥有自定义用户模型可能会更好。