models.py
from django.db import models
class Images(models.Model):
def upload_path(instance, filename):
return '/images/'.join([filename])
image = models.ImageField(upload_to=upload_path, blank=True, null=True)
logits = models.BinaryField()
#customer = models.ForeignKey(Customer ,on_delete=models.DO_NOTHING, default=None)
class Customer(models.Model):
customer_id = models.BigIntegerField(unique=True)
first_name = models.CharField(max_length=300)
last_name = models.CharField(max_length=300)
images = models.ForeignKey(Images ,on_delete=models.DO_NOTHING, default=None)
def __str__(self):
return str(self.customer_id)
My problem is i want to be able to assign multiple images to single user which should be possible because of ForeignKey but i don't seem to get it to work like that.
I want multiselect field just like in manytomanyfield but in foreignkey field.
CodePudding user response:
My problem is [I] want to be able to assign multiple images to [a] single user which should be possible because of
ForeignKeybut [I] don't seem to get it to work like that.
No: A ForeignKey is a many-to-one relation: it means that many Customers can refer to a, possibly the same, single Images. If you want to use multiple Images then you need to write the ForeignKey in the opposite direction, so:
from django.db import models
class Image(models.Model):
def upload_path(instance, filename):
return f'/images/{filename}'
image = models.ImageField(upload_to=upload_path, blank=True, null=True)
logits = models.BinaryField()
customer = models.ForeignKey(
'Customer',
on_delete=models.SET_NULL,
null=True,
related_name='images'
)
class Customer(models.Model):
customer_id = models.BigIntegerField(unique=True)
first_name = models.CharField(max_length=300)
last_name = models.CharField(max_length=300)
def __str__(self):
return f'{self.customer_id}'
