简体   繁体   中英

How to get data from 2 different models in Django

I am new at this, trying to learn new django and python tricks

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 app 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. 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

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:

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')

and you can retrieve all items for an author by:

user.items.all() in python and user.items.all in Django template.

For additional reference about relationships and foreign key please visit:

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

Hope this helps!

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