Home > Mobile >  Queryset filter() in Django with ForeignKey
Queryset filter() in Django with ForeignKey

Time:10-30

I'm having trouble with Django queryset. First of all, what I want to do is to receive from the customer which discount coupons (dc for short) he/she used and then compare with the ones already in the system. And I did manage to do it with 1

my view:

    @login_required(login_url='login')
    def cupons(request):
       produtos = Produto.objects.all()
       cliente = Cliente.objects.get(user=request.user)
       pedido = Pedido.objects.all().get(cliente=cliente)
    return render(request, 'cupons.html', {'lista': produtos, 'venda': pedido.produto.cupom})

The succesfull result enter image description here

P.S: There are 2 Usado (Used) because they have the same "dc"

The problem starts when the user used 2 or more "dc", it says that get() received more than 1 result and after some research I found that I need to use filter, but someone can explain me how can achieve the same result using filter ?

My classes are Cliente (Client), Produto (Product) and Pedido (Order).

my model:

class Cliente(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ...

class Produto(models.Model):
    STATUS = (
        ('Novo', 'Novo'),
        ('Expirado', 'Expirado'),
        ('Usado', 'Usado'),
    )

    ...
    ...
    cupom = models.CharField(max_length=200, null=True)
    ...

class Pedido(models.Model):  
    cliente = models.ForeignKey(Cliente, null=True, on_delete=models.SET_NULL)
    produto = models.ForeignKey(Produto, null=True, on_delete=models.SET_NULL)
    ...

Just for sure my html:

                      {% for i in lista %}
                        <tr>
                            <td ><img src="{{i.lojista.imagem}}" class="logo_lojista"> </td>
                            <td> {{i.nome}}</td>
                            <td><a class="btn btn-outline-danger  btn-sm btn-block td_cupom" href="{% url 'liberar_form' i.id %}" >Liberar Cupom</a></td>
                            {%if venda != i.cupom %}
                            <td class="td_status"> {{i.status}}</td>
                            {%else%}
                            <td class="td_status">Usado</td>
                            {%endif%}
                            <td class="td_desconto"> {{i.desconto}}</td>
                            <td class="td_estoque"> {{i.estoque}}</td>
                        </tr>
                    {% endfor %}

Using the code below I've got the result of a queryset with a list with my Order numbers, now I want to extract the cupom (coupon) field from the Product (FK). Can someone help me ?

  @login_required(login_url='login')
def cupons(request):
    produtos = Produto.objects.all()
    cliente = Cliente.objects.get(user=request.user)
    pedido = Pedido.objects.all().filter(cliente=cliente)


    return render(request, 'cupons.html', {'lista': produtos, 'venda': pedido})

Result from the filter: <QuerySet [<Pedido: Pedido: 1>, <Pedido: Pedido: 2>]>

CodePudding user response:

Instead of retrieving the order (pedido) records, you can retrieve the products (produtos) of the client (cliente), or even the coupons (cupoms) of the products (produtos) that belongs to the client (cliente). To do that, you can use values_list as follows:

cupoms_usado = Pedido.objects.filter(cliente=cliente).values_list("produto__cupom", flat=True)

It will join two tables (Pedido & Produto) and give you the list of coupons that are used by the client. Then you can simply check if the coupon of the list is in the list of used coupons.

{% if i.cupom in cupoms_usado %}

Note: Do not forget to pass cupoms_usado to your template from the related view.

  • Related