I have an app with a similar structure as this snippet
class Blog(models.Model):
name = models.CharField(max_length=25)
class Category(models.Model):
name = models.CharField(max_length=25)
blog = models.ForeignKey(Blog)
class Entry(models.Model):
title = models.CharField(max_length=25)
category = models.ForeignKey(Category)
What is the most generic way, that i will be able to use in other apps to fetch all blogs with their category and entries?
I thought about creating a manager for the Blog model, that can fetch all the Categories for that blog, but it's hardcoding the model names
class BlogManager(models.Manager):
def categories(self):
return Category.objects.filter(blog=self)
Any suggestions?
What you want is a Select Related. It returns a QuerySet that will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query. Your query for Blogs would look something like:
Blog.objects.select_related().filter( something )
or
Blog.objects.select_related().get( something )
Why not use a standard way?
Filter using Blog's PK with FK relation.
Category.objects.filter(blog__pk=self.pk)
Related
The django documentation is pretty clear on how to look up fields on single instances but what about reverse relationship QuerySet objects.
Example:
class Author(models.Model)
name = models.Charfield(...)
class Book(models.Model)
title = models.Charfield(...)
author = models.ForeignKey(Author, ...)
I now create a queryset object:
special_books = Book.objects.filter(title__icontains="Space")
Now, I want to find all authors that belong to special_books. I want to do something like this:
special_books.authors.all()
Without doing this:
authors = []
for book in special_books:
authors += book.author
Is there a way to do this easily?
Use the referenced Model name (Book in lowercase) to make your query:
Author.objects.filter(book__title__icontains="Space")
If you have a related_name defined in your foreignKey :
class Book(models.Model)
title = models.Charfield(...)
author = models.ForeignKey(Author, related_name="books")
Your queryset would be :
Author.objects.filter(books__title__icontains="Space")
Quoting Django's documentation :
Related managers support field lookups as well. The API automatically follows relationships as far as you need. Use double underscores to separate relationships. This works as many levels deep as you want.
Simply do the lookup on Author model that spans relationship
Author.objects.filter(book__title__icontains="Space")
If having different books stored in django database, each book has a date in which it was added to the database. Is their a way of filtering books written by a certain author that was within a date range only using django views?
Not sure what you mean by only django views, I assume you want to use querysets. Your question is poorly written - read this.
class Book(models.Model):
title = models.CharField(max_length=200)
date = models.DateTimeField()
author = models.ForeignKey(Author)
class Author(models.Model):
name = models.CharField(max_length=200)
And Queryset would be something like this.
books = Book.objects.filter(author__name=authors_name,
date__range=["2011-01-01", "2011-01-31"])
I got Person object with foreign key to contact model. Contact has first_name field.
Howe do I search by that first_name field?
models:
class Person(models.Model):
(...)
contact = models.ForeignKey('addressbook.Contact', on_delete=models.CASCADE)
(...)
class Contact(models.Model):
last_name = models.CharField("Nazwisko", max_length="40", blank=False)
first_name = models.CharField("ImiÄ™", max_length="40", blank=False)
(...)
view:
class personListPlus(SortableListMixin, SearchableListMixin, ListView):
model = Person
search_fields = ['contact__first_name','contact__last_name']
paginate_by = 20
template_name = 'list_plus.html'
sort_fields = ['contact__first_name', 'contact__last_name' ]
Sorting works just fine but I'm no sure how to create GET search request.
I tried http://{VIEW_URL}?q=contact__first_name=ADAM
but in response I got : Related Field has invalid lookup: icontains
What am I doing wrong?
Newer versions of django have a security feature which prevents lookups on related models.
The workaround can be found on this question:
Django: Filtering by %filter% not allowed
You cannot specify which of the fields will be searched in the query parameter of the URL. Your URL should look like this:
http://{VIEW_URL}?q=ADAM
This will search in both contact__first_name and contact__last_name fields, since those are the fields specified by the *search_field* attribute of your view.
You can have a look at the get_queryset method of the SearchableListMixin class to see how the query is parsed and of the class handles both the query parameter and the search fields.
Django has a unique_for_date property you can set when adding a SlugField to your model. This causes the slug to be unique only for the Date of the field you specify:
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(unique_for_date='publish')
publish = models.DateTimeField()
What would be the best way to achieve the same kind of functionality for a non-DateTime field like a ForeignKey? Ideally, I want to do something like this:
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(unique_for='category')
category = models.ForeignKey(Category)
This way I could create the following urls:
/example/category-one/slug
/example/category-two/slug
/example/category-two/slug <--Rejected as duplicate
My ideas so far:
Add a unique index for the slug and categoryid to the table. This requires code outside of Django. And would the built-in admin handle this correctly when the insert/update fails?
Override the save for the model and add my own validation, throwing an error if a duplicate exists. I know this will work but it doesn't seem very DRY.
Create a new slug field inheriting from the base and add the unique_for functionality there. This seems like the best way but I looked through the core's unique_for_date code and it didn't seem very intuitive to extend it.
Any ideas, suggestions or opinions on the best way to do this?
What about unique_together?
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(db_index=False)
category = models.ForeignKey(Category)
class Meta:
unique_together = (('slug','category'),)
# or also working since Django 1.0:
# unique_together = ('slug','category',)
This creates an index, but it is not outside of Django ;) Or did I miss the point?
I want to sort a QuerySet of contacts by a related field. But I do not know how.
I tried it like this, but it does not work.
foundContacts.order_by("classification.kam")
Actually in a template I can access the kam value of a contact through contact.classification.kam since it is a OneToOne relationship.
The (simplified) models look like this:
class Classification(models.Model):
kam = models.ForeignKey(User)
contact = models.OneToOneField(Contact)
class Contact(models.Model):
title = models.ForeignKey(Title, blank=True, null=True)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
It should be:
foundContacts.order_by("classification__kam")
Here is a link for the Django docs on making queries that span relationships: https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships
You can also see some examples in the order_by reference:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.order_by
as the documentation indicates, it should be used as in queries about related models
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#order-by
foundContacts.order_by("classification__kam")
I've struggled a lot with this problem, this is how I solved it:
contact ordered by "kam" (Classification) field:
show_all_contact = Contact.objects.all().order_by(title__kam)
classification ordered by Users email (no sense in it, but only show how it works):
show_all_clasification = Classification.objects.all().order_by(kam__email)