简体   繁体   中英

How to filter foreign key in django filter

I want to get the username using the field user (foreignkey)

I don't know how get the username in the view

model.py

class Publication(models.Model):
user =  models.ForeignKey(User, on_delete=models.CASCADE)

filters.py

class PublicationFilter(django_filters.FilterSet):
user = django_filters.CharFilter(lookup_expr='exact')
class Meta:
    model = Publication
    fields = ['user']

views.py

def publication_list(request):
f = PublicationFilter(request.GET, queryset=Publication.objects.all())
return render(request, 'info/filter.html', {'filter':f})

html

<h2>Lista de sus informes</h2>


        <p class="profile-data">

             <div class="col-md-4 mt-2 mb-3 ">
          <div class="row p-1">
            <div class="col-md-12">


            <form action="" method="get" >
                <b> {{ filter.form.as_p }} </b><br>
                <button type="submit">Search</button>
            </form>

              <ul>
               <b>{% for profile in filter.qs %} </b><br>

              <b>{{ profile.nombre }} </b><br>
                <b>{{ profile.user }} </b><br>

               <a href="{% url 'profiles:detail' profile.user %}">Ver     perfil</a><br>

              {% endfor %}

您可以使用'__': Publication.objects.filter(user__username="John Doe")

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