2010-03-15 80 views
1

我使用Django表单。我遇到的问题是外键字段和使用初始字段的字段会获取所有相关条目(与该记录相关的所有记录,除了我想要的那个条目之外),例如获取主键,主键,帖子主题,帖子主体以及该记录归因的所有其他值)。表单和其他相关的查询仍然正常,但是这种行为阻塞了我的数据库。我如何获得特定字段而不是所有记录。我的模型的一个例子是这里:childParentIdDjango表单,外键和初始返回所有相关的值

表单字段返回postID,单独postSubjectpostBody而不是postID

另外form = ForumCommentForm(initial = {'postSubject':forum.objects.get(postID = postID), })返回与postID相关的所有记录。

class forum(models.Model): 
postID = models.AutoField(primary_key=True) 
postSubject = models.CharField(max_length=25) 
postBody = models.TextField() 
postPoster = models.ForeignKey(UserProfile) 
postDate = models.DateTimeField(auto_now_add=True) 
child = models.BooleanField() 
childParentId = models.ForeignKey('self',blank=True, null=True) 
deleted = models.BooleanField() 

def __unicode__(self): 
    return u'%s %s %s %s %s' % (self.postSubject, self.postBody, self.postPoster, self.postDate, self.postID 

回答

0

我有点想通了以下几点。

forms.py

class ForumCommentForm(forms.ModelForm): 
    postBody = forms.CharField(widget=forms.Textarea(attrs={'cols':'70', 'rows':'5'})) 
    childParentId = forms.CharField(widget=forms.TextInput) 
    class Meta: 
     model = forum 

views.py

@login_required DEF forum_view(请求,帖子ID):

post = list(forum.objects.filter(postID = postID)|forum.objects.filter(childParentId__in = postID)) 

if request.method == 'POST': 

    form = ForumCommentForm(request.POST) 
    if form.is_valid(): 
     form.save() 
     #this reloads the query to include updated values 
     post = list(forum.objects.filter(postID = postID)|forum.objects.filter(childParentId__in = postID)) 
     #this returns an empty form 
     form = ForumCommentForm() 

else: 
    parent = forum.objects.get(postID = postID) 
    form = ForumCommentForm(initial = {'postSubject':parent.postSubject, 'child':'1', 'childParentId':parent.postID})