繁体   English   中英

django-同时显示两个字段以创建唯一的模型

[英]django - display both fields for a unique together model

我在Django中有一个模型,通过unique_together设置了“复合主键”。

对于下面的模型,我可以设置str()结果,以便显示两个字段(名称和供应商)

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')

这样它也将出现在相关模型中,例如

class ProductPrices(models.Model):
    name = models.ForeignKey(Product)

unique_together不是复合主键。 这只是一个复合约束。 您的模型仍然具有一个隐藏的,自动生成的id字段,它是真正的主键。

是的,您可以设置__str__来输出您想要的任何东西,只要它是字符串即可。 它不一定是唯一的,但如果确实是,它确实会有所帮助。 (顺便说一句,我不确定您使用的是哪个Python,或者在Python 3中它是否会更改,但是建议您使用__unicode__而不是__str__ 。)

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

但这又不是您的实际主键。 也要查看(不建议这样做,因为它很吵):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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