Search code examples
djangodjango-modelsmodel

Django: Populate a model field from another model's field and make both amendable by admin


I want to create a database where an admin user can add products via the admin portal. The products will have a category field. I want the admin to also be able to add/remove category types. However I'm relatively new to django and can't work out how to do this. I feel like I need to use a ForeignKey but I'm getting confused about how I link it to the specific category name.

I created a Category model and a Product model:

class Category(models.Model):
    created_on = models.DateTimeField(auto_now_add=True)
    category_image = CloudinaryField('image', default='placeholder')
    category_name = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.category_name


class Product(models.Model):
    created_on = models.DateTimeField(auto_now_add=True)
    main_image = CloudinaryField('image', default='placeholder')
    item_name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(default="", null=False)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    style = models.ForeignKey(Category, related_name='category_name', on_delete=models.CASCADE)
    likes = models.ManyToManyField(User, related_name='product', blank=True)

    def __str__(self):
        return self.item_name

I've tried to link the style field in the Product model so that it pulls it's data from the category_name field in the Category model. Is this possible? Can I get it to appear as a dropdown on the admin portal somehow? Any help much appreciated!


Solution

  • Rather then relating to a category_name, you have related the product a category class, which will have category_name and other fields related to the category class.

    Let's say you get product

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

    Now to get both models appear in admin panel then you have to register the models in the your-app/admin.py file of you app.

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