简体   繁体   中英

How to search a Django database using a field saved in the model?

I am trying to create a search bar that searches for users in my Journal app. I want to redirect the search to the appropriate page if the user exists. I have created the view function, template and URL for the feature.

As a test, I imported the User class from django.contrib.auth.models and I was able to display a personalised message if the user existed.

def search_user(request):
"""Search for users."""

if request.method == "POST":
    searched = request.POST["searched"]
    usernames = User.objects.filter(username__icontains=searched)
    context = {"searched": searched, "usernames": usernames}
    return render(request, "journals/search_user.html", context)

In the main model, the Journal class has a ForeignKey relation with User and it is saved to a field called "owner". I would like to somehow check if the searched username matches with this "owner" field. When I try to make a search this way, it cannot find any data. The reason I want the search to refer to "owner" is so that I can access the other fields in the table. Could someone point out the mistake I am doing here?

from django.db import models
from django.contrib.auth.models import User

class Journal(models.Model):
    """A particular subject the user may want to write about."""

    name = models.CharField(max_length=100)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        """Return a string representation of the model."""

        return self.name


class Entry(models.Model):
    """Something specific the user may want to add to the journal."""

    journal = models.ForeignKey(Journal, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    date_edited = models.DateTimeField(auto_now=True)


**View Function:**

def search_user(request):
    """Search for users."""

    if request.method == "POST":
        searched = request.POST["searched"]
        usernames = Journal.objects.filter(owner=searched)
        context = {"searched": searched, "usernames": usernames}
        return render(request, "journals/search_user.html", context)

searched is just a text string, and Journal.owner is actually a User , so nothing will match here.

Match the related username instead ...

usernames = Journal.objects.filter(owner__username=searched)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM