简体   繁体   中英

Python django Need return name instead of id foreginkey

class Product(models.Model):
    name = models.CharField(max_length=300, default='default name')
    description = models.TextField(max_length=800, blank=True, null=True)
    link = models.TextField(default='0')
    type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=True, blank=True)
    category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, null=True, blank=True)
    keyword = models.OneToOneField(KeyWords, on_delete=models.CASCADE, null=True, blank=True)

model don't return data from ForeignKey

I think you need to define a __str__ method in your ProductCategory model. This way you will have a descriptive name for each entry into that table. Without it, your entry is best described by the id field.

p = Product.objects.get(...)
p.type.name
p.category.name

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