Reputation: 7498
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)
Upvotes: 0
Views: 377
Reputation: 42835
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)
Upvotes: 1