comp make that a variable of a database has the total of records that another bank owns?

Asked

Viewed 44 times

-3

opa, me nome antonio, I’m starting in December, I’m creating an application where I need the totmatérias attribute of the table "Writer" to have the number of news written by that writer that is stored in the other table, any help? follows the code:

from datetime import datetime
from django.utils import timezone
from django.db import models
from django.db.models.fields import CharField, DateField

class Noticias(models.Model):
    titulo = models.CharField(max_length=30, help_text='maximo: 30 caracteres')
    data = models.DateField(auto_now=False, auto_now_add=True)
    editado = models.DateField(auto_now=True, auto_now_add=False)
    escritor = models.ForeignKey('Escritor', on_delete=models.PROTECT)
    texto = models.CharField(max_length=1000)
    resumo = models.CharField(max_length=100, help_text='Um breve resumo da matéria principal, de no maximo 100 caracteres.')

    def __str__(self): return f'{self.titulo} - {self.data}'

class Escritor(models.Model):
    id = models.IntegerField(primary_key=True)
    nome = models.CharField(max_length=50, help_text='maximo 50 caracteres')
    totmatérias = ???
    nascimento = DateField(auto_now=False, auto_now_add=False)
    cidadeNatal = CharField(max_length=40, help_text='cidade onde voce nasceu')

    def __str__(self): return f'{self.id} - {self.nome}'

as seen in the code, I want that in the Writer class, in the variable totmatérias contains the total of written subjects by the same writer that are in the subjects class. Ex: if the writer 1 registered 5 subjects, I want to stay 5 in the totmatérias of this writer. I hope you have given to understand, thanks already Dsd.

1 answer

0

Create this field as integer:

totmatérias = models.IntegerField()

When you want this table, Voce makes the logic and sends the number you want...

You can override save method, so that when saving, do this desired logic:

class Escritor(models.Model):
    id = models.IntegerField(primary_key=True)
    totmatérias = models.IntegerField()
    ...

    def save(self, *args, **kwargs):
        numero_total = Noticias.objects.filter(escritor=self.nome).count()
        self.totmatérias = numero_total
        return super().save(*args, **kwargs)

This code above is for reference only.. It depends a lot on what exactly you need. It shouldn’t work that way.. If you want to test the logic and send possible errors, we can adjust.

  • thanks for your help, I’ll test

Browser other questions tagged

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