1

Let's say I have a model defined as such

class BlogPost(Models.Model):
    """ Defines a blog model """
    blog    = models.TextField()
    blog_id = models.AutoField(primary_key=True)
    author  = models.CharField()

I want to define some method that accesses the blog posts of a certain author, say 'john doe'. How would I go about defining a method to access all of the blog posts owned by john doe, and then put their blog_id's into a python list?

def selectPostsByUser(user):
""" Implement function to select all object """

NOTE: please disregard the poor representation of the data fields. They are purely arbitrary, I just put names to remove ambiguity from the example.

4

4 回答 4

1

模型.py

class BlogPost(Models.Model):
    """ Defines a blog model """
    blog    = models.TextField()
    blog_id = models.AutoField(primary_key=True)
    author  = models.CharField()

    @classmethod
    def selectPostsByUser(cls, user):
        return cls.objects.filter(author=user)

视图.py

user = "john doe"
blogs = BlogPost.selectPostsByUser(user)
于 2013-03-29T01:58:13.240 回答
1

我希望您的模型中有一个用户外键:

def selectPostsByUser(user):
    return self.objects.filter(user__id=user.id).values_list('blog_id', flat=True)

如果您传递给该selectPostsByUser方法的用户是作者(和用户模型对象)。然后,您应该将 author 作为模型中的 ForiegnKey 字段。

于 2013-03-29T01:32:33.927 回答
0

您的author字段应该是ForeignKey,而不是CharField. 这就是您在 Django 中表示关系的方式。

然后,Django 允许您检索与用户关联的帖子对象:user.blog_set.all(). 从那里,提取 ID 是微不足道的。

此外,Django自动id为 objects 提供一个字段,您不需要定义自己的blog_id字段。


遵循Django“民意调查”教程应该会为您提供构建应用程序所需的所有工具。

于 2013-03-29T01:32:39.390 回答
0

直接回答这个问题,假设作者其实是一个‘CharField’。您可以执行以下操作以从“jane doe”获取所有博客文章,然后将所有 ID 放入列表中......

posts = BlogPost.objects.filter(author='jane doe')
list = []
for items in posts:
    lists.append(items.blog_id)
于 2013-03-29T06:34:58.033 回答