simone/django-compositekey

Composite primary key generation/display of m2m join tables

Closed this issue · 3 comments

The composite primary key of an m2m join table row appears to be incorrect if it consists of two other model objects (instead of a varchar for example).

This is best demonstrated with an example

# models.py
from django.db import models
from compositekey import db


class Author(models.Model):
    name = models.CharField(max_length=100)


class Book(models.Model):
    title = models.CharField(max_length=100)


class BookAuthor(models.Model):
    id = db.MultiFieldPK('author', 'book')
    author = models.ForeignKey('Author')
    book = models.ForeignKey('Book')
# Using the django shell
>>> author = Author()
>>> author.name = "Charles Darwin"
>>> author.save()
>>> 
>>> book = Book()
>>> book.title = "Origin of the Species"
>>> book.save()
>>> 
>>> ba = BookAuthor(author=author, book=book)
>>> ba.save()
>>> 
>>> print author.pk
1
>>> print book.pk
1
>>> print ba.pk
Author object-Book object
>>> 

The issue is that the primary key of the book author (ba.pk) is not unique when
quering the python instance.

The fix for this issue is relatively simple and a patch is included.
https://gist.github.com/3957348

The only thing that needs to be modified is the function assemble_pk in utils.py
where a check has been added to test if one of the "values" is a django Model.

The patch was generated using the version of the code on PyPI (which I noticed
is slightly different to the one in github)

thanks for your support.

check if it is ok
b844b18

Thanks for putting in the fix so quickly!

I'll give it a test on Monday when I am back in the office.

Works as advertised.

Thanks again!