how to output data from a linked table in django?

Question:

I have a built-in User table and a Note table associated with it by key.

class Note(models.Model):
    header = models.CharField(max_length=100)
    note_text = models.TextField()
    data = models.DateField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

That is, a registered user may have several notes. How do I get all these notes from this particular user (who has now visited his page)? I need to get these notes in views.py.

I tried different ways, don’t know how to do that.

Asked By: Elena

||

Answers:

Hope this answer finds you well …

First, you already have a user object in your request. But, still you want to filter out notes for other users too, then do

get_user = User.objects.get(id=id)    # For any random user
get_user = request.user               # For authenticated user

After getting the user, you simply filter it with the Note model like this …

get_notes = Note.objects.filter(user=get_user)

You are good to go!

Answered By: techbipin
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.