Django外键objects.get究竟该怎么写,djangoobjects.get,model定义如下:cl


model定义如下:

class Tag(models.Model):    id = models.AutoField(primary_key=True)    name = models.CharField(max_length=100,verbose_name='名称')    def __unicode__(self):        return self.nameclass Post(models.Model):    id = models.AutoField(primary_key=True)    author = models.ForeignKey(User)    post_date = models.DateField(verbose_name='日期', auto_now=True)    post_title = models.CharField(verbose_name='标题', max_length=100)    post_content = RichTextField(verbose_name='内容')    post_tag = models.ForeignKey(Tag, verbose_name='标签')

在views.py里我是这样写的:

def tag(request, tag):    post_list = Post.objects.filter(post_tag.name = tag)    return render_to_response('tag.html',{'post_list':post_list,'tag':tag})

直接报语法错误Unresolved reference ‘post_tag’,如果写成post_tag = tag,网页上会报

ValueError at /tag/test/invalid literal for int() with base 10: 'test'Request Method:     GETRequest URL:    http://127.0.0.1:8000/tag/test/Django Version:     1.7.1Exception Type:     ValueErrorException Value:    invalid literal for int() with base 10: 'test'

就是想筛选下post_tag等于tag的Post,究竟该怎么写?

post_tag 这里是一个对象

pythondef tag(request, tag):    tag = Tag.object.get(name=tag)    post_list = Post.objects.filter(post_tag=tag)    return render_to_response('tag.html',{'post_list':post_list,'tag':tag})

django 的orm 查询属性不是用 . 而是用 __连接的,题主可以试试

post_list = Post.objects.filter(post_tag__name=tag)

编橙之家文章,

评论关闭