4

I use django nonrel/djangoappengine on google app engine. It is not possible to specify composite primary keys directly. However it should be possible to emulate this behaviour. I am wondering about what is the best approach.

Problem

Conside the following datamodel

class AccumuatedSales(models.Model):
    salesman = models.ForeignKey(Salesman)
    year = models.Postiveinteger()
    totalSales = models.PositiveInteger()

I want (salesman, year) to be treated as a primary key. That is, if I do

asby1 = AccumulatedSales(salesman='Joe', year=2010, totalSales=100)
asby1.save()
asby2 = AccumulatedSales(salesman='Joe', year=2010, totalSales=200)
asby2.save()

The 'table' AccumulatedSales should contain one row. So the second save overwrites the first.

Possible Solution

class AccumuatedSales(models.Model):
    key = models.CharField(primary_key=True,, default=None, editable=False)
    salesman = models.ForeignKey(Salesman)
    year = models.Postiveinteger()
    totalSales = models.PositiveInteger()

    def save(self):
        self.key = someHashFunction(self.salesman_id, self.year)
        super(AccumulatedSales, self).save()

Questions

  • is this approach good or "the right one"?
  • What is the best datatype for the field key? Personally I would like to have som 128-bit field, but that is not available to my knowledge.
dreftymac
  • 31,404
  • 26
  • 119
  • 182
MrJ
  • 1,436
  • 2
  • 15
  • 21

1 Answers1

0

This looks like a pretty good solution.

dragonx
  • 14,963
  • 27
  • 44