Home > database >  In Django how I can create automatically a many to many entry based on a field found in two models
In Django how I can create automatically a many to many entry based on a field found in two models

Time:12-04

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.

CodePudding user response:

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.
  • Related