简体   繁体   English

如何从 Django 中的 2 个不同模型中获取数据

[英]How to get data from 2 different models in Django

I am new at this, trying to learn new django and python tricks我是新手,正在尝试学习新的 django 和 python 技巧

I am making a project where authors can upload a design, the name of this app is "score" where there model.py as shown below:我正在制作一个作者可以上传设计的项目,这个应用程序的名称是“score”,其中 model.py 如下所示:

score app model.py评分应用 model.py

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    design = models.ImageField(
        blank=False, null=True, upload_to='')

I also have another app which is called "core" where there is an Item model.我还有另一个名为“核心”的应用程序,其中有一个项目 model。 I want to be able manually from the admin to chose the name of the author and in the next design choice i only get his uploaded designs.我希望能够从管理员手动选择作者的姓名,并且在下一个设计选择中我只得到他上传的设计。

I know I have to make a tuple of choice我知道我必须做出选择的元组

here is the core app model.py这是核心应用程序 model.py

class Item(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField()
    design= models.ImageField()

You need to use Foreign keys to maintain relationship between items and users.您需要使用外键来维护项目和用户之间的关系。 So in class Item it will be:所以在 class 项目中它将是:

author = models.ForeignKey(User, on_delete=models.CASCADE)

and for getting all the designs or items of an author you can use:并且要获取作者的所有设计或物品,您可以使用:

user.design_set.all()

or或者

Design.objects.filter(author.id=request.user.id)

or for your Foreign key you can set a related_name such as items so your code will be: author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='items')或者对于您的外键,您可以设置相关名称,例如项目,因此您的代码将是: author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='items')

and you can retrieve all items for an author by:您可以通过以下方式检索作者的所有项目:

user.items.all() in python and user.items.all in Django template. user.items.all()user.items.all模板中的 user.items.all。

For additional reference about relationships and foreign key please visit:有关关系和外键的更多参考,请访问:

https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_one/ https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_one/

Hope this helps!希望这可以帮助!

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

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