Custom select on DJANGO

Asked

Viewed 715 times

1

model py.

class Produto(models.Model):

    nome=models.CharField('nome', max_length=100)

    marca=models.CharField('nome', max_length=100)

    categ=models.ForeignKey(Produto, verbose_name='Produto')


class Categ(models.Model):

    categ_desc=models.CharField('categ', max_length=100)

I wonder how I do for a select, as below, and convert to JSON the result:

select a.nome,a.marca,b.categ_desc from Produto a inner join Categ b on a.id=b.id

I’m doing so, but it doesn’t bring the description of the table categ.

Produto.objects.select_related()
  • That’s right the part a.id = b.id? Would not be a.categ = b.id?

  • Yes misspelled. But I need with Django to display the information of the 2 tables.

1 answer

1

Simple as that:

class Categ(models.Model):
    categ_desc=models.CharField('categ', max_length=100)
    def __str__(self):
       return self.categ_desc

class Produto(models.Model):
    nome=models.CharField('nome', max_length=100)
    marca=models.CharField('marca', max_length=100) 
    categ=models.ForeignKey(Produto, verbose_name='Produto')

produtos = Produto.objects.all()

If you run the command print produtos[0] Voce will obtain the first record of the Product table, with all the information, including the related field, in this case categ, note that if Voce does not set the function __str__ the categ field will come as an object. A good practice is to define __str__ for all your Model classes.

Obs.:
I changed the name of the tag field because it was duplicated with the product name.

Browser other questions tagged

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