[Answered ]-Accessing data from Django model

1👍

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.

1👍

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)

0👍

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.

0👍

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)

Leave a comment