简体   繁体   中英

Django model field dependent on instance

I am trying to create a model field that is dependent on an instance (specifically an instance of a foreign key).

Example:

class User(models.Model):
    name = models.CharField()
    ...

class Entry(models.Model):
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=user.name)

As you can see, I want the file "upload_to" parameter to be dependent on the user. Is there an easy way to do this?

upload_to may also be a callable, such as a function, which will be called to obtain the upload path, including the filename.

This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system.

def _upload_to(instance, filename):
    return str(instance.user.name)

class Entry(models.Model):
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=_upload_to)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM