I have 3 django models, where the first has a foreign key to the second, and the second has a foreign key to the third. Like this:
class Book(models.Model):
year_published = models.IntField()
author = models.ForeignKey(Author)
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
agent = models.ForeignKey(LitAgent)
class LitAgent(models.Model):
agent_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
I want to ask for all the literary agents whose authors had books published in 2006, for example. How can I do this in Django? I have looked at the documentation about filters and QuerySets, and don't see an obvious way. Thanks.
LitAgent.objects.filter(author__book__year_published=2006)
Related
class Author(models.Model):
name = models.CharField(max_length=50)
class Chapter(models.Model):
book = models.ForeignKey(Album, on_delete=models.CASCADE)
author = models.ManyToManyField("Author")
class Book(models.Model):
author = models.ManyToManyField("Author")
I am trying to show all related authors when I visit one author detail. To do that currently I do this to achieve this:
authors = []
for chapter in Author.objects.get(id=id).chapter_set.all():
authors.append(chapter.artists.all())
Is there any other way to do this by djangoORM
You can follow ManyToManyField relationships backwards in filters, in the case of the Author model you should be able to use chapter__ to access the Chapter.author relationship
authors = Author.objects.filter(chapter__author_id=id).distinct()
So I Am Making A Shop Website I wanted to ask how do we add tables as a field? Do we use foreign key or something in Django I am using SQLite btw
https://i.stack.imgur.com/W1Y5H.png
I think you want to use model fields as table fields. Basically, you require ORM(Object-relational mapping). I am adding a basic model snippet below with a foreign key added.
class Collection(models.Model):
title = models.CharField(max_length=255)
# This for foreign key .The plus sign means that a reverse relation won't be created!
featured_product = models.ForeignKey('Product',on_delete=models.SET_NULL,null=True,related_name='+')
class Product(models.Model):
sku = models.CharField(max_length=10,primary_key=True)
title = models.CharField(max_length=255)
slug = models.SlugField(default='-')
description = models.TextField()
unit_price = models.DecimalField(max_digits=6,decimal_places=2)
inventory = models.IntegerField()
last_update = models.DateTimeField(auto_now=True)
collection = models.ForeignKey(Collection,on_delete=models.CASCADE)
While playing around with the ManyToManyField, I wondered is there a way you can query a ManyToManyField automatically the same way you'd do a ForeignKey using select_related()?
Tables:
class Author(models.Model):
fullname = models.CharField(max_length=100)
class Foo(models.Model):
bar = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
foo = models.ForeignKey(Foo)
author = models.ManyToManyField(Author)
In order to get the data I need from Book I usually do:
book = Book.objects.select_related('foo').get(pk=1)
authors = book.author.all()
which makes 2 trips. Is there a way to combine them the way select_related() does?
You can use prefetch_related for M2M field
Book.objects.select_related('foo').prefetch_related('author').values('author', 'title').get(pk=1)
I have three models, each with a primary key. How can I perform join operation using rest framework in Django?
These are tables:
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
there are really good examples here:
http://www.django-rest-framework.org/api-guide/relations/
This page explains how you can include the authors names when serializing book,
and also how to easily include a list of books when serializing the author.
If you want to be able to provide an API for publisher, you can easily provide a list of books using the methods in the link above.
http://www.django-rest-framework.org/api-guide/relations/#reverse-relations
I have the following models:
class Author(models.Model):
author_name = models.CharField()
class Book(models.Model):
book_name = models.CharField()
class AuthorBook(models.Model):
author_id = models.ForeignKeyField(Author)
book_id = models.ForeignKeyField(Book)
With that being said, I'm trying to emulate this query using the Django ORM (select all of the books written by a specific author, noting that Authors can have many books and Books can have many Authors):
SELECT book_name
FROM authorbook, book
WHERE authorbook.author_id = 1
AND authorbook.book_id = book.id
I've read this FAQ page on the Django website, but before I modify my model structure and remove AuthorBook, I was curious if I could emulate that query using the current structure.
You should be able to do:
books = Book.objects.filter(authorbook__author_id=1)
to get a QuerySet of Book objects matching your author_id restriction.
The nice thing about Django is you can cook this up and play around with it in the shell. You may also find
http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships
to be useful.
"AuthorBook" seems not correctly modeled.
You should use a ManyToManyField:
class Book(models.Model):
name = models.CharField()
authors = models.ManyToManyField(Author)
Then you can do:
books = Book.objects.filter(authors__id=1)