Make custom select on DJANGO

0

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 would like to know how to do a select , as below, and convert the result to JSON:

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

I'm doing this, but it does not contain the description of the categ table.

Produto.objects.select_related()
    
asked by anonymous 22.06.2017 / 21:42

1 answer

0

Simple like this:

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 execute the command print produtos[0] you will get the first record of the Product table, with all the information, including the related field, in this case categ , note that if you do not define the function __str__ the field categ will come as an object. A good practice is to set __str__ to all your Model classes.

Note:
I changed the field name tag as it was duplicated with the product name.

    
24.06.2017 / 15:08