0

I have a model in django with a 'compound primary key' setup via unique_together.

for the model below can I set up the str() result so that it display both fields, (name and supplier)

class Product(models.Model):
    name = models.CharField(max_length=255)
    supplier = models.ForeignKey(Supplier)
    # some other fields

    def __str__(self):
        return self.name

    class Meta:
        unique_together = ('name', 'supplier')

So that it will also appear in a related model eg.

class ProductPrices(models.Model):
    name = models.ForeignKey(Product)
Yunti
  • 6,761
  • 12
  • 61
  • 106

1 Answers1

1

unique_together isn't a compound primary key. It's just a compound constraint. Your model still has a hidden, autogenerated id field which is the real primary key.

Yes, you can set up __str__ to output whatever you want so long as it's a string. It doesn't have to be unique, but it really helps if it is. (BTW, I'm not sure which Python you're using or if this changes in Python 3, but it's recommended to use __unicode__ instead of __str__.)

def __unicode__(self):
    return "{0} (from {1})".format(self.name, self.supplier)

But again, this isn't your actual primary key. To see that as well (not really recommended, because it's noise):

def __unicode__(self):
    return "{0} (from {1}) (#{2})".format(self.name, self.supplier, self.id)
Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96
  • Thanks, (I'm aware unique_together isn't a compound primary key, but often used as a proxy for this in django as it doesn't seem to have this feature) I didn't realise any string would work. That did it. In the end I implemented a callable instead as I preferred the two fields in separate columns so these could be sorted etc.. see here http://stackoverflow.com/questions/163823/can-list-display-in-a-django-modeladmin-display-attributes-of-foreignkey-field – Yunti Nov 27 '15 at 09:30
  • Django's lack of proper compound primary key support is a PITA especially since there are a nontrivial number of databases with them and it's hard to interface with them because of this. And yeah, most of us add model or admin methods for display purposes so we can have different columns. – Mike DeSimone Nov 28 '15 at 15:05