[Answer]-Django Integrity Error – id cannot be null

1πŸ‘

βœ…

All you need for this is:

class ProjectTerms(models.Model):
    terms = models.CharField(max_length=100)

class ProjectLinks(models.Model):
    links = models.CharField(max_length=100)
    relations = models.ManyToManyField(ProjectTerms)

The ID fields and the table for the ManyToManyField will be automatically created.

To set the ManyToMany relationship, use add:

def create_models(my_term, my_link):
    (saved_term, created) = ProjectTerms.objects.update_or_create(terms = my_term)
    (saved_link, created) = ProjectLinks.objects.update_or_create(links = my_link)
    saved_link.relations.add(saved_term)
    saved_link.save()

Leave a comment