1

I am working on a django blog app and i want to access all the fields of database through foreign key of other database .

class User(AbstractUser):
    about_user = models.TextField(("Profile"),blank = True)

    def __str__(self):
        return self.username
    

class Post(models.Model):
    author = models.ForeignKey("account.User",on_delete=models.CASCADE)
    status = models.BooleanField(("Status"),default = False)

Now I want to access all the data of user database from post something like

posts = Post.objects.filter(status = True)
posts.author.about_author
or
user = User.objects.filter(username = post.author)
user.about_author

what i am trying here in my template all the content of post will display and after that i want the about_author (whoever wrote the post ).kinda like how stackoverflow shows every questions.

Thanks in advance and any advice would be much appreciated.

1 Answer 1

1

You fetch the Posts with:

posts = Post.objects.filter(status=True)

but it makes no sense to write:

posts.author

since posts is a QuerySet (so a collection) of Posts, not a single one.

You can enumerate over the posts and then show the .authors for all Post objects:

for post in posts:
    print(post.author.about_user)

or in the template with:

{% for post in posts %}
    {{ post.author.about_user }}
{% endfor %}

You can boost efficiency by fetching all the Users in the same query with:

posts = Post.objects.filter(status=True).select_related('author')
Sign up to request clarification or add additional context in comments.

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.