Django模型从同一模型插入外键

时间:2013-02-03 05:28:31

标签: django-models

我正在Django构建一个简单的评论应用程序。该应用程序允许回复评论,并使用相同的模型来存储评论和回复。我的问题是当我尝试插入新的回复时,父帖(FK到父注释)插入为NULL。当我使用管理界面插入回复时,它会正确存储我选择的父帖的父帖ID。所以我知道问题不在我的模型范围内,而是在我看来。

/ MODEL /

class UserPost(models.Model):

name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
                        help_text='Unique value for product page URL, created from name.', editable = False)


post = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255, blank = True, null = True,
                                 help_text='Content for description meta tag')
meta_description = models.CharField(max_length = 255, blank = True, null = True,
                                    help_text = 'Content for description meta tag')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
parentpost = models.ForeignKey('self', blank = True, null = True)

class Meta:
    #app_label = ''

    db_table = 'userposts'
    ordering = ['created_at']
    verbose_name_plural = 'UserPosts'

def __unicode__(self):
    return self.name

@models.permalink   
def get_absolute_url(self):
    return ('lync_posts', (), {'posts_slug': self.slug})

def save(self):
    if not self.id:
        d = datetime.datetime.now()
        s = d.strftime('%Y-%M-%d-%H-%M-%S-%f')

        slugfield = str(self.name + s)
        self.slug = slugfield

        super(UserPost, self).save()

/ VIEW /

def reply(request, slugIn):

parentpostIn = UserPost.objects.get(slug = slugIn)

pid = parentpostIn.id
template_name = 'reply.html'

if request.method == 'POST':
    form = forms.ReplyPostForm(data = request.POST)
    # create a new item

    if form.is_valid(): # All validation rules pass
        # Process the data in form.cleaned_data
        # ...
        if form.is_valid():
            nameIn = form.cleaned_data['name']
            postIn = form.cleaned_data['post']

            newPost = UserPost(name = nameIn, post = postIn, parentpost = pid)
            newPost.save()
    return render_to_response(template_name, locals(), context_instance = RequestContext(request))

else:
    # This the the first page load, display a blank form
    form = forms.NewPostForm()

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

return render_to_response(template_name, locals(), context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:0)

您正尝试按ID设置Parentpost ForeignKey。

你应该使用:

newPost = UserPost(name = nameIn, post = postIn, parentpost = parentpostIn)

或(见Django: Set foreign key using integer?):

newPost = UserPost(name = nameIn, post = postIn)
newPost.parentpost_id = pid