简体   繁体   English

如何在Django的同一模型中获取与ForeignKey相关的主键(pk)?

[英]How to get the foreignKey related primary key (pk) in the same model in django?

I need to get the id (pk) of a related model.foreignKey object in order to set the "upload_to" attr of a model.FileField of the same model. 我需要获取相关model.foreignKey对象的ID(pk),以便设置同一模型的model.FileField的“ upload_to”属性。

Something like this: 像这样:

class myClass(models.Model):
    related_model = models.ForeignKey(RelatedModel,on_delete=models.CASCADE)
    file = models.FileField(upload_to=str(related_model.id)+"/")

So for example, if the related_model has the primary_key 10 the upload_to attr has to be "10/" 因此,例如,如果related_model具有primary_key 10,则upload_to attr必须为“ 10 /”

It is possible or I have to set that value in the view.py file when the object is created? 创建对象时是否可能需要在view.py文件中设置该值?

Use a callable as the upload_to parameter. 使用callable作为upload_to参数。

def related_path(instance, filename):
    return '{}/{}'.format(instance.related_model_id, filename)

class myClass(models.Model):
    related_model = models.ForeignKey(RelatedModel,on_delete=models.CASCADE)
    file = models.FileField(upload_to=related_path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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