user1876508
user1876508

Reputation: 13172

Accessing data from Django model

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.

Upvotes: 1

Views: 86

Answers (4)

Nick Siemsen
Nick Siemsen

Reputation: 1

To answer this question directly, let's say that the author is actually a 'CharField'. You could just do the following to get all blog posts from 'jane doe' and then put all the IDs into a list....

posts = BlogPost.objects.filter(author='jane doe')
list = []
for items in posts:
    lists.append(items.blog_id)

Upvotes: 0

catherine
catherine

Reputation: 22808

models.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)

views.py

user = "john doe"
blogs = BlogPost.selectPostsByUser(user)

Upvotes: 1

Thomas Orozco
Thomas Orozco

Reputation: 55303

Your author field should be a ForeignKey, not a CharField. This is how you represent relationships in Django.

Django then allows you to retrieve the post objects associated with an user: user.blog_set.all(). From there, it is trivial to extract the IDs.

Also, Django automatically provides an id field for objects, you don't need to define your own blog_id field.


Following the Django "polls" tutorial should give you all the tools you need to build your app.

Upvotes: 0

Aamir Rind
Aamir Rind

Reputation: 39709

I hope you have a Foreign Key to user in your model:

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

If the user which you are passing to the selectPostsByUser method is the author (and User model object). Then you should have author as a ForiegnKey field in your model.

Upvotes: 1

Related Questions