How to search by related model field using django-extra-views? - django

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.

Related

Reverse ManyToMany lookup for model with filter

I am trying to use Django ManyToMany reverse lookup with filtering, values_list and order_by but can't figure it out.
Here is my model (simplified):
class Project(Model):
users = ManyToManyField(User, verbose_name="Users", related_name="project_users", blank=True)
files = ManyToManyField(FileInfo, verbose_name="Files", related_name="project_files",)
class FilInfo(Model):
# Name
name = CharField(_("Name"), max_length=300, blank=False)
# Description
description = TextField(
_("Description"),
max_length=4096,
validators=[MaxLengthValidator(4096)],
)
# User model is a standard Django user model
I am trying to get all distinct FileInfo.name for all Projects where self.request.user is a project_user
Here is my obviously wrong attempt as a placeholder: // Doesn't even compile :(
FileInfo.objects.values_list('name').filter(Q(pk = project__files__pk) & Q(project__users__pk=self.request.user.id)).distinct().order_by("-" + order_by)
From the FileInfo object you can access Projects through project_files related name, and then filter the users field for the user.
FileInfo.objects.filter(
project_files__users=self.request.user
).values_list('name').distinct().order_by("-" + order_by)

Django fetch all relations

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)

django views - accessing a m2m field in a generic view

I've stumbled upon this issue and my noob brain got fried trying to resolve it. I feel like there's some basic concepts here that I'm missing.
So I have this "Films" model with category choice field and a m2m relationship to a "Directors" model, and I'm trying to write 2 different views, one that returns a list of films filtered by category and one that returns a list of films filtered by director.
The first one is easy, but I just don't know how to get the director model's name field to create the second filter.
So I have this models (i've taken the irrelevant stuff out including the category thing i mentioned above)
class Director(models.Model):
name = models.CharField(max_length=50)
web = models.URLField(blank=True, help_text= "opcional")
class Film(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length= 15)
director = models.ManyToManyField(Director, blank=True, help_text= "opcional")
this url
(r'^peliculas/director/(?P<director>\w+)/$', 'filtered_by_director'),
and this view
def filtered_by_director(request,director):
return list_detail.object_list(
request,
queryset = Film.objects.filter(director.name=director),
template_name ='sections/film_list.html',
template_object_name = 'film',
paginate_by = 3
)
The same template is supposed to be used by both views to render the relevant list of objects
The view doesn't like the filter i'm using at the queryset for the m2m field, but I have no clue how to do it really, I've tried whatever I could think of and it gives me a "keyword can't be an expression" error
Any help to this lowly noob will be appreciated.
Line queryset = Film.objects.filter(director.name=director),
needs to read: queryset = Film.objects.filter(director__name=director),
Field lookups are done by __ double underscore syntax:
http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups
In your filter, try specifying the director name like (documentation):
filter(director__name=director)

django manytomany through

If I have two Models that have a manytomany relationship with a through model, how do I get data from that 'through' table.
class Bike(models.Model):
nickname = models.CharField(max_length=40)
users = models.ManyToManyField(User, through='bike.BikeUser')
The BikeUser class
class BikeUser(models.Model):
bike = models.ForeignKey(Bike)
user = models.ForeignKey(User)
comment = models.CharField(max_length=140)
And I would add a user to that bike (presuming I have a myBike and a myUser already)
BikeUser.objects.create(bike = myBike, user = myUser, comment = 'Got this one at a fancy store')
I can get all the users on 'myBike' with myBike.users.all() but how do I get the 'comment' property?
I would like to do something like
for myBikeUser in myBike.users.all():
print myBikeUser.comment
The through table is linked by standard ForeignKeys, so you do a normal ForeignKey lookup. Don't forget that there's a comment for each bikeuser, ie one for each bike/user pairing.
for myBikeUser in myBike.bikeuser_set.all():
print myBikeUser.comment, myBikeUser.user.first_name

How to create a unique_for_field slug in Django?

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?