简体   繁体   English

Django:参考数据库条目

[英]Django: Reference Database Entry

I wanna set to the user a background profile image. 我想为用户设置背景个人资料图像。 But instead of letting him place any image, I'll give some pics to let him choose. 但是,我不会给他放置任何图像,而是给一些图片让他选择。 So I first was storing the images URLs in the Django code, and insert them directly into the database. 因此,我首先将图像URL存储在Django代码中,然后将其直接插入数据库中。 But I think is more practical to store in a database all the images urls I want with their name, and then reference back into the database the image name. 但是我认为将所有想要的图像URL及其名称存储在数据库中,然后将图像名称重新引用到数据库中是更实际的。

So I have: 所以我有:

class BackgroundImage(models.Model):
    url = models.PositiveSmallIntegerField()
    name = models.CharField(max_length=25)

class User(models.Model):
    ...
    bgpic = <here it goes the code>

How can I reference a database entry of this model into my user URL profile? 如何在我的用户URL配置文件中引用此模型的数据库条目?

I think you are looking to add a foreign key reference on the User table to the BackgroundImage table 我认为您正在寻找将User表上的外键引用添加到BackgroundImage表中

class BackgroundImage(models.Model):
    url = models.PositiveSmallIntegerField()
    name = models.CharField(max_length=25)

class User(models.Model):
    ...
    bgpic = models.ForeignKey(BackgroundImage)

Then you will be able to set a references and access the values of the row attached via foreign key: 然后,您将能够设置引用并访问通过外键附加的行的值:

user = User.objects.get(id=1)

# set the fk reference
user.bgpic = BackgroundImage.objects.get(id=2)
user.save()

# access the reference  
print user.bgpic.url
print user.bgpic.name

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

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