2012-03-14 72 views
0

我目前有三類User,UserProfileVendorUser是來自from django.contrib.auth.models import User的內置Django。另外兩個是如下(Django)如何將Limit_choices_設置爲ManyToManyField指向的另一個類?

這裏是UserProfile

class UserProfile(models.Model) : 
    TYPE_CHOICES = (
     ('t', 'tenant'   ), 
     ('m', 'property manager'), 
     ('o', 'property owner' ), 
     ('v', 'vendor'   ), 
     ('w', 'web user'  ), 
     ('x', 'other'   ), 
    ) 
    user  = models.ForeignKey(User, unique = True) 
    user_type = models.CharField(max_length = 1, choices = TYPE_CHOICES, default = 't') 

User.profile = property(lambda u : UserProfile.objects.get_or_create(user = u)[ 0 ]) 

這裏是Vendor

class Vendor(models.Model) : 
    def __unicode__(self) : 
     return self.name 

    name = models.CharField(max_length = 135) 
    users = models.ManyToManyField(User, null = True, blank = True) 

我想限制Vendor.users只UserUserProfile.user_typevendor

如何使用limit_choices_to。我可以這樣做......

users = models.ManyToManyField(User, null = True, blank = True, limit_choices_to = { UserProfile.objects.filter(user = self.users).user_type : 'm' }) 

我知道上面的代碼將拋出一個錯誤,但希望你能看到我想要做的事。

在此先感謝!

+0

您是否嘗試過limit_choices_to = {'profile__user_type':'m'}?這將更適合limit_choices_to的工作方式。 – Arthur 2012-03-14 23:39:50

回答

1

我能夠與

manager = models.ForeignKey(User, related_name = 'manager', limit_choices_to = { 'userprofile__user_type' : 2 }) 

做到這一點,其中2是物業經理在UserType類的主鍵(user_type_id)。

相關問題