gpt4 book ai didi

python - Django - 获取存储在外键中的对象

转载 作者:行者123 更新时间:2023-12-01 05:56:53 24 4
gpt4 key购买 nike

Possible Duplicate:
Django FileField with upload_to determined at runtime

我正在创建一个网络应用程序,允许用户在线存储文件,例如 Dropbox。用户的文件由模型 Item 建模:

from django.db import models
from django.contrib.auth.models import User


class Item(models.Model):
# Name of file
name = models.CharField(max_length=200)

# Site user who owns the file
user = models.ForeignKey(User)

# Path to file in database
# Python complains here since "username" is an attribute of the User class, not
# an attribute of ForeignKey.
file = models.FileField(upload_to=(user.username + '/' + name))

现在,如果您查看 FileField 的 upload_to 参数,我想指定文件在数据库中的存储位置。如果我有一个用户“bill”,其文件为“myfile”,那么他的文件应该位于“bill/myfile”路径下。

为了获取这个字符串,我尝试了“user.username + '/' + name”,但是python提示用户没有属性用户名,因为用户不是用户对象:它是存储用户的外键。所以问题是,如何从代码中的ForeignKey获取用户对象?

现在关于 Django 的数据库 API 不起作用,因为在我可以使用 API 之前必须将对象保存到数据库中。情况并非如此,因为我在构造 Item 对象期间需要数据。

最佳答案

使用 FileField,您可以将 [upload_to 上的函数][1]

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to

关于python - Django - 获取存储在外键中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12047064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com