simone / django-compositekey

Django Composite Multiple PrimaryKey
77 stars 16 forks source link

Composite primary key generation/display of m2m join tables #15

Closed khoobks-gaiaresources closed 12 years ago

khoobks-gaiaresources commented 12 years ago

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)

simone commented 12 years ago

thanks for your support.

check if it is ok https://github.com/simone/django-compositekey/commit/b844b18b52dfa7a052ec3fabf5226a121604b69e

khoobks-gaiaresources commented 12 years ago

Thanks for putting in the fix so quickly!

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

khoobks-gaiaresources commented 12 years ago

Works as advertised.

Thanks again!