Search code examples
pythondjangodatabasemodel

how to output data from a linked table in django?


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.


Solution

  • 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!