简体   繁体   中英

django - display both fields for a unique together model

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM