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 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yes __ is intentional and that is how field lookups works. See here
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)

Comments

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.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.