Django:从另一个模型的字段填充一个模型字段,并使两者都可由管理员修改

iovurdzv  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(171)

我想创建一个数据库,管理员用户可以通过管理门户网站添加产品。产品将有一个类别字段。我希望管理员也能够添加/删除类别类型。然而我对django相对来说是个新手,不知道怎么做。我觉得我需要使用ForeignKey,但我对如何将其链接到特定类别名称感到困惑。
我创建了一个Category模型和一个Product模型:

  1. class Category(models.Model):
  2. created_on = models.DateTimeField(auto_now_add=True)
  3. category_image = CloudinaryField('image', default='placeholder')
  4. category_name = models.CharField(max_length=50, unique=True)
  5. def __str__(self):
  6. return self.category_name
  7. class Product(models.Model):
  8. created_on = models.DateTimeField(auto_now_add=True)
  9. main_image = CloudinaryField('image', default='placeholder')
  10. item_name = models.CharField(max_length=50, unique=True)
  11. slug = models.SlugField(default="", null=False)
  12. price = models.DecimalField(max_digits=8, decimal_places=2)
  13. style = models.ForeignKey(Category, related_name='category_name', on_delete=models.CASCADE)
  14. likes = models.ManyToManyField(User, related_name='product', blank=True)
  15. def __str__(self):
  16. return self.item_name

我尝试链接Product模型中的style字段,以便它从Category模型中的category_name字段提取数据。这可能吗?我可以让它以某种方式在管理门户上显示为下拉列表吗?任何帮助非常感谢!

i34xakig

i34xakig1#

与category_name不同,您将产品与category类相关联,它将具有category_name和与category类相关的其他字段。
假设你拿到货了

  1. product = Product.objects.first()
  2. product.style.category_name # will get you the product name

现在,要让两个模型都出现在管理面板中,那么您必须在应用程序的your-app/admin.py文件中注册模型。

  1. admin.site.register(Category)
  2. admin.site.register(Product)

相关问题