Last record of each Django object

Asked

Viewed 705 times

0

I am developing a web application in Python, Django and Sqlite. I have two models, one for "Seller" and one for "Orders". I need to take the last order of each seller and I’m not able to do this with Django. Follow my models below:

class Vendedor(models.Model):
    nome = models.CharField(verbose_name='Nome', max_length=100)
    nascimento = models.DateField(verbose_name='Data Nascimento:', 
                                  help_text='Informe a data')
    endereco = models.TextField(verbose_name='Endereço:')

class Pedidos(models.Model):
    vendedor = models.ForeignKey('Vendedor', verbose_name='Vendedor:',
                                  related_name='vend', on_delete=models.SET_NULL,
                                  null=True)

    data = models.DateField(verbose_name='Data Pedido:', help_text='Informe a data')

    LISTA_TIPO = (('Of', 'Oficina'),('Pd', 'Produto'),('Sr', 'Serviço'),)

    tipo = models.CharField(verbose_name='Tipo:', max_length=50,
                            choices=LISTA_TIPO, blank=True,
                            help_text='Informe qual o tipo', default='')

Each seller has several orders. I need to pick up the last order from each seller. Someone could help me

  • After editing, your question has become totally disfigured and too comprehensive I suggest you read it carefully that link, here at Sopt

  • Okay, now yes, try to implement my answer in the command line, if you can’t, add to the question or here in the comments what went wrong, if you get and continue with problems in another topic then you should probably elaborate another question.

  • Thank you for your help. I followed your logic and it worked, thank you very much!!

1 answer

0


As in Django there are several contexts, I will try to explain with your own example but in a Django console, if you want to try, enter a python console (in the environment and directory of your project) and execute the code below (Explanations are like comments in the code itself):

Creating the objects:

# Importação dos pacotes necessários
from datetime import date
from core.models import Vendedor, Pedidos

# Criando 2 vendedores
>>> Vendedor.objects.create(nome='foo', nascimento='1991-01-01', endereco='Rua que sobe e desce, 166')
>>> Vendedor.objects.create(nome='bar', nascimento='1992-02-02', endereco='Rua que sobe e desce, 777')

# Listando a queryset dos objetos vendedores
>>> Vendedor.objects.all()
<QuerySet [<Vendedor: Vendedor object (1)>, <Vendedor: Vendedor object (2)>]>

# Adicionando 2 pedidos para o vendedor 1
Pedidos.objects.create(vendedor=Vendedor.objects.get(pk=1),data=date.today(), tipo='of')
<Pedidos: Pedidos object (1)>
Pedidos.objects.create(vendedor=Vendedor.objects.get(pk=1),data=date.today(), tipo='Pd')
<Pedidos: Pedidos object (2)>

# Adicionando 2 pedidos para o vendedor 2
Pedidos.objects.create(vendedor=Vendedor.objects.get(pk=2),data=date.today(), tipo='Pd')
<Pedidos: Pedidos object (3)>
Pedidos.objects.create(vendedor=Vendedor.objects.get(pk=2),data=date.today(), tipo='Sr')
<Pedidos: Pedidos object (4)>

# Listando todos os pedidos (QuerySet)
print(Pedidos.objects.all())
<QuerySet [<Pedidos: Pedidos object (1)>, <Pedidos: Pedidos object (2)>,
           <Pedidos: Pedidos object (3)>, <Pedidos: Pedidos object (4)>]>

Working with Objects.last():

# Apresentando o ultimo pedido feito:
print(Pedidos.objects.last())
Pedidos object (4)

Working with objects.filter():

# Apresentando o ultimo pedido do vendedor 1
Pedidos.objects.filter(vendedor=1).last()
<Pedidos: Pedidos object (2)>

# Apresentando o ultimo pedido do vendedor 2
Pedidos.objects.filter(vendedor=2).last()
<Pedidos: Pedidos object (4)>

Working with related_name:

# Apresentando o ultimo pdido do vendedor 1 via related name
>>> vendedor1 = Vendedor.objects.get(pk=1)
>>> vendedor1.vend.last()
<Pedidos: Pedidos object (2)>

Submitting the last request of each seller in one pandas.DataFrame():

>>> data = []
>>> vendedores = Vendedor.objects.all()
>>> for v in vendedores:
        ultimo_pedido = v.vend.last()
        data.append([v.nome, ultimo_pedido.id, ultimo_pedido.data, ultimo_pedido.tipo])

>>> ultimos_pedidos = pd.DataFrame(data, columns=['Vendedor', 'Id Pedido','Data', 
                                                  'Tipo'])
>>> print(ultimos_pedidos)
    Vendedor  Id Pedido        Data Tipo
 0      foo           2  2019-04-18   Pd
 1      bar           4  2019-04-18   Sr
  • First thank you so much for the great explanation. I’m starting programming and I couldn’t replicate your code in my program. the following error appears: Exception Type: Attributeerror Exception Value: 'Nonetype' Object has no attribute 'week' .

  • See that my code is an example in a python terminal, it is not to put in your program, you can even trigger a terminal to play "ipsis Litteris" my example as long as it is in the directory of your project and in the same environment. I suggest you remove the comments made in the question, because it would disturb someone who had the same problem, make the comments here, or we can go to the chat area.

  • 1

    I would like to thank you for your help. I followed your logic and it worked. I have implemented it in my program and it worked!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.