2012-11-24 98 views
3

我有以下模式:django的模型形式的过滤器查询集

class Article(models.Model): 

    title = models.CharField() 
    description = models.TextField() 
    author = models.ForeignKey(User) 


class Rating(models.Model): 

    value = models.IntegerField(choices=RATING_CHOICES) 
    additional_note = models.TextField(null=True, blank=True) 
    from_user = models.ForeignKey(User, related_name='from_user') 
    to_user = models.ForeignKey(User, related_name='to_user') 
    rated_article = models.ForeignKey(Article, null=True, blank=True) 
    dtobject = models.DateTimeField(auto_now_add=True) 

基于以上模型,我已创建的模型的形式,如下所示:

模型形式:

class RatingForm(ModelForm): 

    class Meta: 
      model = Rating 
      exclude = ('from_user', 'dtobject') 

不包括from_user,因为request.userfrom_user

表单呈现良好,但在to_user的下拉字段中,作者也可以评价自己。所以我想将current_user的名称填充到下拉字段中。我该怎么做?

+0

但为什么选项中不包括作者呢? –

回答

7

覆盖__init__可从to_user选项中移除当前用户。

更新:更多的解释

ForeignKey的使用ModelChoiceField,其选择是查询集。因此,在__init__中,您必须从to_user的查询集中删除当前用户。

更新2:实施例

class RatingForm(ModelForm): 
    def __init__(self, current_user, *args, **kwargs): 
     super(RatingForm, self).__init__(*args, **kwargs) 
     self.fields['to_user'].queryset = self.fields['to_user'].queryset.exclude(id=current_user.id) 

    class Meta: 
     model = Rating 
     exclude = ('from_user', 'dtobject') 

现在,在视图,其中在创建RatingForm对象通request.user作为关键字参数current_user这样。

form = RatingForm(current_user=request.user) 
+0

可否请您详细说明一个例子。 – whatf

+0

希望你有想法。 –