简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM