Good day, not so long ago, working with Django.
Encountered the following problem.
There are two models
class Product(models.Model):
productID = models.AutoField(primary_key=True)
brandID = models.ForeignKey(Brand, verbose_name=u'Бренд')
categoryID = models.ForeignKey(Category, verbose_name=u'Категория')
productPhotos = models.ManyToManyField("ProductPhoto", verbose_name = "Фотографии товара", related_name="photos", blank=True)
class ProductPhoto(models.Model):
productPhotoID = models.AutoField(primary_key=True)
productID = models.ForeignKey(Product)
imageFile = models.FileField(u'Путь к изображение', upload_to=makeUploadPath)
dateModified = models.DateField(auto_now=True)
For admin use the following TabularInline
class ProductPhotoInline(admin.TabularInline):
model = ProductPhoto
verbose_name = u"Фото"
verbose_name_plural = u"Фотографии"
class ProductAdmin(admin.ModelAdmin):
list_display = ('title')
search_fields = ...
fieldsets = ...
)
inlines = [ ProductPhotoInline, ]
The problem when you add a product in the table ProdcutPhoto productId field is filled, and the field in the table Products productPhotos is empty. How best to do to fill both fields.
You should remove the productPhotos ManyToMany field, it’s redundant. If each photo is only attached to one product, then the productID ForeignKey is all you need.
To access the photos from a product instance, you can use
productphoto_set, e.g.