0

I want to set a dynamic upload_to in the ImageField fields using a method. Something like this:

def content_file_name(instance, filename):
    return '/'.join(['content', instance.database_alias, filename])

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=content_file_name)

Update

I don't know if is this useful, but I'm using Django 1.7.1

I'm doing a test with the model above:

models.py

from django.db import models


def content_file_name(instance, filename):
    print "INSTANCE(%s)" % instance._state.db
    return "/".join(instance._state.db, filename)


class Cliente(models.Model):

    class Meta:
        verbose_name = "Cliente"
        verbose_name_plural = "Clientes"

    Nombre = models.CharField("Nombre", max_length=50)
    Foto = models.ImageField(upload_to=content_file_name)

    def __unicode__(self):
        return "Hello World"

    MY_FIELDS = ["Nombre", "Foto"]

I'm getting in terminal on form submit:

Terminal

INSTANCE(None)
[19/May/2015 21:19:55] "POST /default/clientes/new HTTP/1.1" 500 168242

Another option could be making an import and get the database alias, but I don't know where get this from yet.

Community
  • 1
  • 1
MikeVelazco
  • 885
  • 2
  • 13
  • 30

2 Answers2

0

instance._state.db should return the database alias.

Adrian Ghiuta
  • 1,569
  • 16
  • 29
0

In Django 2.2.14, you can access the database alias using instance.db

qryset_employee = Employees.objects.using('OrgChartDatabase')
print(qryset_employee.db) ## Prints 'OrgChartDatabase'
Yi Zong Kuang
  • 544
  • 1
  • 6
  • 17