1

I'm playing with querysets in django.

What I'm looking it's to save a new foreign product or item but I can not achieve it.

shell

from applaboratorio.models import Datos_empresa_DB, Datos_equipo_DB

detalle = Datos_empresa_DB.objects.filter(pk=58)

resp = Datos_equipo_DB(equipo='dell-labtop',marca='dell', modelo='432423',Foraneo_Datos_empresa_DB = detalle)

models.py

class Datos_empresa_DB(models.Model):
    nombre = models.CharField(max_length=150)
    empresa = models.CharField(max_length=150)

class Datos_equipo_DB(models.Model):
    Foraneo_Datos_empresa_DB = models.ForeignKey(Datos_empresa_DB)
    equipo = models.CharField(max_length=300)
    marca = models.CharField(max_length=300)
    modelo = models.CharField(max_length=300)

What am I doing bad?

I'm trying to create a new product for a client that already exist in db.

1
  • You should include your models definition so we can tell what is the shape of the tables. Commented Oct 16, 2016 at 17:45

1 Answer 1

2

I think you're nearly there. You need to call the save method of the new product to save to the DB, and to retrieve the related client object, you should get not filter so you have the object itself and not a list of objects (or QuerySet):

detalle = Datos_empresa_DB.objects.get(pk=58)
#                                  ^^^
resp = Datos_equipo_DB(equipo='dell-labtop',marca='dell', modelo='432423',Foraneo_Datos_empresa_DB =detalle)
#                                          Save on model's related field <-^^^^^^^
resp.save()
Sign up to request clarification or add additional context in comments.

4 Comments

This. Or, alternatively, resp = Datos_empresa_DB.objects.create(equipo='dell-labtop', marca='dell', modelo='432423', detalle=detalle)
@spectras Yes, that too :)
Are you sure guys?
@Elarquitecto Change detalle to Foraneo_Datos_empresa_DB in the model instantiation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.