this is excellent explanation thank you
I had to modify the models a bit and give the OneToOne unique related_name, like this,
Application model
class Application(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="userapp", db_index=True, primary_key=True)
dob = models.DateField(blank=True, null=True)
age = models.IntegerField(blank=True, null=True)
ImageModel
class ImageModel(models.Model):
""" save head, body image to media folder, generate a thumbnail img from head img """
def wrapper(instance, filename, target):
ext = filename.split(".")[-1].lower()
if ext not in ["jpg", "png", "gif", "jpeg"]:
raise ValidationError(f"invalid image extension: {filename}")
if ext == "jpeg":
ext = "jpg"
if instance.pk:
filename = os.path.join("images", f"{instance.pk}_{target}.{ext}".lower())
else:
filename = os.path.join("images", f"{filename}_{target}.{ext}".lower())
if os.path.lexists(f"{settings.MEDIA_ROOT}/{filename}"):
os.remove(f"{settings.MEDIA_ROOT}/{filename}")
return filename
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="userimg", db_index=True, primary_key=True)
head_img = models.ImageField(null=True, blank=True, upload_to=partial(wrapper, target="head"))
body_img = models.ImageField(null=True, blank=True, upload_to=partial(wrapper, target="body"))
thumb_img = models.ImageField(null=True, blank=True) # same as head_img but resized and shrunk on quality
and then in my view I can get data from all 3 tables
def search(request):
if request.method == "POST":
# query both Application and Image models
queryset = Application.objects.all()
context = {"search_form": ApplicantSearchForm, "search_data": queryset, "media": settings.MEDIA_URL}
else:
context = {"search_form": ApplicantSearchForm}
return render(request, "search.html", context=context)
and in my template, I see the image paths coming from the ImageModel table,
search.html
{% for d in search_data %}
{{ d.age }} << Application data
{{ d.user.last_login }} << User data
{{ d.user.userimg.head_img }} << ImageModel data
{% endfor %}
much cleaner than raw sql, thank you