Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
In Django how I can create automatically a many to many entry based on a field found in two models

I have the following models example:

class TestSet(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Class(models.Model):
    name = models.CharField(max_length=50)
    test_set_id = models.ForeignKey(TestSet)

    def __str__(self):
        return self.name

class Test(models.Model):
    title = models.CharField(max_length=50)
    test_set_id = models.ForeignKey(TestSet)

    def __str__(self):
        return self.title

class ClassTest(models.Model):
    class_id = models.ForeignKey(Class)
    test_id = models.ForeignKey(TestSet)
    memo = models.CharField(max_length=250)

    def __str__(self):
        return self.memo

What I want to do is when a new Class or Test is created, it should also create automatically a ClassTest entry if their test_set_id matches with the currenct entries on the database.

Example:

  1. Lets say I already have three Test objects with test_set_id = 1
  2. I create a new Class object with test_set_id = 1
  3. After creating the new Class object, the program should also create 3 new entries in the ClassTest model connecting classes to tests based on the match of the test_set_id field.
  4. It should work the same if a new Test object is added.
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

So there are two answers that comes in mind:

  1. You can use Django Signals to create a receiver that execute a specific command when a Class object is created. Something around the code below. Consider that the instance is basically the just created class and you can simply operate standard django query with that do get and create additional objects.
@receiver(post_save, sender=Class)
def create_test_sets(sender, instance, created, **kwargs):
    if created:
        ///do things///
        
  1. On a second beat thought, I would ask what's the overall use-case your are trying to solve. I feel there is some redundancy here but I can't fully figure out where unless you help me gather the bigger picture.
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda