Django ManyToMany relation add() error

10,205

Adding prt directly should work on first try. How are you retrieving pl and prt? Assuming you have some data in your database, try those commands from the Django shell and see if it works. There seems to be some missing information from the question. After running python manage.py shell:

from yourapp.models import PL
pl = PL.objects.get(id=1)
prt = PRT.objects.get(id=1)
pl.mentionedby.add(prt)
Share:
10,205
viksit
Author by

viksit

The most common mistake people make when designing something completely foolproof, is underestimating the ingenuity of complete fools. - Douglas Adams, Mostly Harmless

Updated on June 04, 2022

Comments

  • viksit
    viksit almost 2 years

    I've got a model that looks like this,

    class PL(models.Model):
        locid = models.AutoField(primary_key=True)
        mentionedby = models.ManyToManyField(PRT)
    
    class PRT(models.Model):
        tid = ..
    

    The resulting many to many table in mysql is formed as,

    +------------------+------------+------+-----+---------+----------------+
    | Field            | Type       | Null | Key | Default | Extra          |
    +------------------+------------+------+-----+---------+----------------+
    | id               | int(11)    | NO   | PRI | NULL    | auto_increment | 
    | PL_id            | int(11)    | NO   | MUL | NULL    |                | 
    | PRT_id           | bigint(64) | NO   | MUL | NULL    |                | 
    +------------------+------------+------+-----+---------+----------------+
    

    Now, if pl is an object of PL and prt that of PRT, then doing

    pl.mentionedby.add(prt)
    

    gives me an error

    Incorrect integer value: 'PRT object' for column 'prt_id' at row 1"

    whereas

    pl.mentionedby.add(prt.tid) 
    

    works fine - with one caveat.

    I can see all the elements in pl.mentionedby.all(), but I can't go to a mentioned PRT object and see its prt.mentionedby_set.all().

    Does anyone know why this happens? Whats the best way to fix it?

    Thanks!