Query Database Table Without Using Foreign Key Django Postgresql - django

I am trying to query a table where I have many records with the same name, on purpose. In my example, I'm using the make of the car, and unfortunately I've already ruled out using a foreignkey. Long story. Anyway, I've been able to determine that I can query the table using a ModelChoiceField and using the distinct command as I'm using Postgresql as shown below:
class Vehicle(forms.Form):
dropdown = forms.ModelChoiceField(queryset=Car.objects.none())
def __init__(self, *args, **kwargs):
super(Vehicle, self).__init__(*args, **kwargs)
self.fields['dropdown'].empty_label = ''
qs = Car.objects.distinct('vehicle_make')
The code above does what I need related to the dropdown, it limits the ModelChoiceField to just the unique values of the vehicle_make of the car.
The challenge is when I go to try to display all of the records with that vehicle_make in my template. I've tried to do a Detail View, but it is only showing me that individual record. That make sense since detail view is just for that record, but I'm trying to figure out how to query the table to show me all of the records with that vehicle_make. I've explored the ChoiceField as well, but can't seem to get this to work either. I've tried several variations of the code below in the template, but nothing seems to work.
{% for vehicle_make in car.queryset %}
{{ vehicle_make }}
{% endfor %}
My model is as follows:
Car(models.Model):
vehicle_make = models.Charfield(max_length=264,unique=False)
def __str__(self):
return self.vehicle_make
Thanks in advance for your input and suggestions.

You can query for all Car objects with a given value for vehicle_make with Car.objects.filter(vehicle_make = 'foo'). For example, this ListView would list all cars:
from django.views.generic.list import ListView
from .models import Car
class CarListView(ListView):
context_object_name = "car_list"
queryset = Car.objects.all()
Whereas this view would list all cars of make 'foo':
class FooCarListView(ListView):
context_object_name = "car_list"
queryset = Car.objects.filter(vehicle_make = 'foo')
One easy way to make this more "dynamic" would be to look for a search query in the url, either as a keyword argument or as a querystring. You could use your existing form to create a URL like this, then parse it in a view. For instance, this view would look for URLs appended with ?search=bar:
class SearchableCarListView(ListView):
context_object_name = "car_list"
def get_queryset(self):
search_term = self.request.GET.get('search', None)
if search_term is not None:
return Car.objects.filter(vehicle_make = search_term)
return Car.objects.all()
Your use case may be better served by using an icontains or iexact lookup, or even by making use of Django's full text search.
In the template for any of these views, you can access all of the Car objects in your queryset like so:
{% for car in car_list %}
{{car}}
{% endfor %}
I hope that I have understood and addressed your question. I am not 100% sure how you are using your form right now, so please let me know if I have overlooked anything there.
After our discussion in the comments, I think you are overcomplicating things with your form, and I think that your lookup might not be doing what you want.
We will get a ValuesQuerySet of all distinct vehicle_make values:
qs = Car.objects.values('vehicle_make').distinct()
(See: Select DISTINCT individual columns in django?)
This returns a ValuesQuerySet that looks like this:
<QuerySet [{'vehicle_make': 'vehicle_make_1'}, {'vehicle_make': 'vehicle_make_2'}...]
Where vehicle_make_1, vehicle_make_2 etc. are your distinct values.
We can give this queryset qs to our template and construct a select element. We could also simplify it first to a list of values to make it easier to work with in the template:
values_list = [ c['vehicle_make'] for c in qs.all() ]
Pass that value to our template and use it to make our select element:
<select name='search'>
{% for vehicle_make in values_list %}
<option value = {{vehicle_make}} > {{vehicle_make}} </option>
{% endfor %}
</select>
From here you have several options. In my opinion, the simplest thing would be using this select element in a form that uses the GET method to construct a search URL like we discussed earlier. Check out the first answer to this question for more info: <form method="link" > or <a>? What's the difference? There is a code snippet in the first answer to that question that can easily be adapted to create a GET-based search form with your newly-created select element.

Related

How to pass dynamic filtering options in django_filters form instead of all model objects?

I have the following structure of the project (models):
Company (based on Groups) <-- Products (foreignKey to Company) <-- Reviews (foreignKey to Products).
Inside template i want to give a user an opportunity to filter reviews by products, but when using django_filters it shows corrects queryset of reviews (related only to company's products) but in filter form dropdown options i can see all products of all companies (even those which are not presented on the page), for example for Company X i see on my page only Cactus and Dakimakura reviews, but in filter form i can select Sausage (but i shouldnt, because its product from another company).
For now it's all looks like this:
#View
def reviewsView(request):
context = {}
user = request.user
company = user.company
products_qset = ProductModel.objects.filter(company=company)
reviews_objects = ReviewModel.objects.filter(product__in=products_qset)
filter = ReviewFilter(request.GET, queryset=reviews_objects)
context['filter'] = filter
return render(request, 'companies/reviews.html', context)
#Filter
class ReviewFilter(django_filters.FilterSet):
class Meta:
model = ReviewModel
fields = [
'product',
'marketplace',
'operator',
'state'
]
#Template
<form action="" method="get">
{{ filter.form.as_p }}
<input type="submit" name="press me" id="">
</form>
<div class="review-list">
{% for i in filter %}
{{i.product}}, {{i.marketplace}} etc.
{% endfor %}
I've done quite a lot of research on django_filters docs and this question seems like duplicate, but i can't fully understand what and why is happening to init in this answer and how to correctly rewrike class ReviewFilter so filter instance would do something like this (in View):
filter = ReviewFilter(request.GET, queryset_to_dispplay=MyQueryset, queryset_to_display_filtering_options=MyQueryset). For now its surely happening because ReviewFilter Meta points to the all table (ReviewModel) objects, instead of filtered beforehands.
I also trying to apply pagination on this page (i cut this from question code for "shortness") and after i will be able to implement filtering i would like to merge those two somehow, but if what i want is not possible - please point me to the right direction (for example: 'you can do this by writing your very own filtering system using some js, no need to use django_filters' or 'with angular.js/view.js/somethingelse you can have it all from the box').

How do I get django template to recognize manytomanyfield comparison?

In my project, I am currently trying to access a manytomany field and compare it to another. I have several cases where I am doing something similar and it is working . The difference in this case is that I am trying to essentially say if one of the values in this many to many field equals a value in this other manytomanyfield, then do something....
Here is my code...
Book(models.Model):
publisher = models.ManyToManyField(Name)
Userprofile(models.Model):
publisher = models.ManyToManyField(Name)
In my Django template I am trying to do something like...
{% If user_publisher in form.initial.publisher_set.all %}
{{ publisher.name }}
{% endif %}
The example above is a simplified version of what I'm trying to do....I'm essentially trying to compare the manytomany fields and if any of the values match, perform an action. I've been at this most of today and have tried several combinations.
If I do something like
{% if user in form.initial.publisher.all %}
This works fine. I'm struggling to try and figure out how I can compare manytomanyfields. I suspect the user query works fine because it's not a manytomanyfield.
I'm thinking my format is off. I have tried to use the _set to publisher and the user publisher and when I go so far as to print the output, I am actually seeing that both the user_publisher and publisher querysets are the same. However, my django template is not showing me any results. Thanks in advance for any thoughts.
I have surfed SO all afternoon as well as Google, but can't quite figure out what I'm doing wrong.
Here is more detail to my issue. I am currently doing a CreateView whereby I am trying to get an existing record by overriding get_initial as shown below:
class BookUpdateView(CreateView):
model = Book
form_class = Book
template_name = 'Book/update_book.html'
def get_initial(self):
initial = super(BookUpdateView, self).get_initial()
book = Book.objects.get(pk=self.kwargs["pk"])
initial = book.__dict__.copy()
initial.update({
"publisher": publisher.all(),
})
return initial
Because I am copying in these records as a starting point and this is a CreateView, I don't yet have a PK or ID to query from a get_context_data perspective. Not sure how to go about getting the data that I am copying in but have not yet saved. I am actually trying to figure out if a user has the same publisher via their user profile and was able to figure out the format for get_context_data as shown below:
def get_context_data(self, **kwargs):
context = super(BookUpdateView, self).get_context_data(**kwargs)
user_publisher = self.request.user.userprofile.publisher.all()
return context
I tried to do something like....
{% if user_publisher in form.initial.publisher_set.all %}
But the template never recognizes that these two in fact do match...
When I print the variables....
They both show...
<QuerySet [<Publisher: ACME Publishing>]>
<QuerySet [<Publisher: ACME Publishing>]>
But the template does not recognize that they are the same. The screen is not rendered as I would expect when using the template language above. No errors, but end result isn't what I would expect either. Thanks in advance for any additional thoughts.
After a day or two of thinking about this, was able to figure out how to grab the PK and then use it in the context so that I could leverage the information via the context and not the form directly.
def get_context_data(self, **kwargs):
context = super(UpdateProcedureView, self).get_context_data(**kwargs)
pk=self.kwargs["pk"]
publisher = Publisher.objects.filter(pk=pk).filter(individual_access=self.request.user).count()
return context
Then in the form I can say something like if publisher > 0 then do something fancy. Thanks for the suggestions along the way to help me think this through.

Modelchoicefield Queryset Confusion

All,
I'm new to Django and have been doing pretty good so far but this one has me stumped. I'm trying to utilize ModelChoiceField for a number of records that have the same name. I'm using Postgresql so I was able to determine that I need to use the distinct command and that is working perfectly. The records in my dropdown are all stripped down to just one version of each of the records. However, when I try to get all of the versions of a particular record, that's where I'm getting lost. I am able to get the detail of each record if I don't use distinct via a DetailView, but I am really trying to get all versions of each record on the screen after the modelchoicefield.
Here is my form:
class History(forms.Form):
dropdown = forms.ModelChoiceField(queryset=History.objects.all())
def __init__(self, user, *args, **kwargs):
super(History, self).__init__(*args, **kwargs)
self.fields['dropdown'].widget.attrs['class'] = 'choices1'
self.fields['dropdown'].empty_label = ''
qs = History.objects.all().distinct('record_name')
self.fields['dropdown'].queryset = qs
I am ultimately trying to get a view the queryset on the screen via my template. I have tried several different versions of code in the template but nothing seems to work. If I use the CBV DetailView without distinct I can get all of the records with their detail view fine. However, that's not what I'm trying to do. I have played with several versions of the queryset command in the template as I found several questions similar to mine but can't seem to get it to work. I found a couple of references to something similar to:
{% for record in form.history.field.queryset %}
etc.
{% endfor %}
But can't seem to get it to work in my Django template. Any and all help is appreciated! Thank you in advance!
In this case I'd either suggest
a) to put the value of your dropdown field into your url matching. See the django docs for named groups in URL. Additionally, you could add an onchange event to your dropdown-field which redirects to <current url>/<value of dropdown> or simply change the value of (if existing) buttons which links to the following page. Caution: With this solution you must ensure that the values of your dropdown field matches url-format (django's slugify might be useful for this).
or
b) to add your dropdown field to your input form or as input field. Then you can extract the value of your dropdown with:
try:
dropdown_value = request.POST['dropdown-field-name'] # dict-error if field is not in request.POST
except:
# some error actions
then you can add this value as filter to your queryset:
def get_queryset(self, dropdown_value=None):
# ...
qs = qs.filter('field-name' = dropdown_value) # possibly no/wrong results if dropdown_value is corrupted or manipulated

How can I display a Django model in a Django template?

Trying to figure out Django... I'd like to build a table in a template that is largely all the data from a Django model. My preference would be to send the model queryset PersonDynamic.objects.all() to the template and have it figure out the column names and then loop through each row, adding the fields for that row. This kind of approach would give me a lot of flexibility because if the model changes the template will automatically change with it.
One approach could be to just move the column headers and each record into lists which I then send to the template but this seems less efficient than just sending the queryset.
What is the best way to do this?
Am I right about efficiency?
Does sending lists rather than model instances come with a larger risk of problems if there are a bazillion records or does that risk exist, regardless of approach?
Thanks!
Try looking at the code for django.contrib.admin, and how the built-in admin site makes tables. The admin site adds a lot of extra features to change how fields are displayed, and what fields to display, but it should give you some idea of how things work.
The absolute simplest way I can think to do what you want is to send the template a list of headers you want to use, and the queryset called with the values_list method. values_list takes a series of field names, and returns another queryset that will yield a tuple of field values instead of a model object. For example, say your PersonDynamic looks like this:
class PersonDynamic(Model):
id = AutoField()
name = CharField()
likes_python = BooleanField()
You could then send something like this to your template:
fields = ['id', 'name', 'likes_python']
qs = PersonDynamic.objects.values_list(*fields)
context = Context({'headers': fields, 'rows': qs})
template.render(context)
And your template could do:
<table>
<tr>{% for item in header %}<th>{{ item }}</th>{% endfor %}</tr>
{% for row in rows %}
<tr>{% for cell in row %}<td>{{ cell }}</td>{% endfor %}</tr>
{% endfor %}
</table>
For your other questions, this will run into problems for larger tables; it takes time and memory to loop over large lists like this, so generally a strategy like pagination is used, where only X items are displayed per page.

Can I create multiple model instances with CreateView?

I have a form whose purpose is to let a user add, edit, subtract and reorder songs. JavaScript DOM manipulation lets users add, subtract and reorder songs fields. The reordering is via jQuery UI's sortable interaction. The order of songs is crucial.
HTML field name attribute values are duplicated. I'm not using Django to generate the form.
Assuming there are two songs on submission, Firebug shows the form DOM looking something like this (csrf omitted):
<form method="post" action="/save/">
<ul id="sortable_songs" class="ui-sortable">
<li>
<input type="text" name="title" id="song_txt_1">
<textarea id="more_info_txtarea_1" name="more_info"></textarea>
</li>
<li>
<input type="text" name="title" id="song_txt_2">
<textarea id="more_info_txtarea_2" name="more_info"></textarea>
</li>
</ul>
<button type="submit">save</button>
</form>
Example query string:
title=FOO&more_info=FOO+INFO&title=BAR&more_info=BAR+INFO
The model:
class Song(models.Model):
title = models.CharField(max_length=65)
more_info = models.CharField(max_length=255)
#todo: foreignkey to User
Probably not much data is involved, both in each record and with regard to the number of records per user. Hence I'm assuming it makes sense that, for a given user, when the form is submitted I'll delete all of their song instances in the Song table and create a bunch of new ones according to the form. (As opposed to having to edit existing records and having a db field which indicates song order).
It seems like I shouldn't write my own view so I'm trying Django's generic CreateView, but perhaps unsurprisingly, with the above user input only a model instance with "BAR" and "BAR INFO" is created -no "FOO" instance is made.
Is there a simple way around this?
You should use Formsets, in this way you can manage multiple instances of an object in a simple way, however you need to control some extra variables and format your query string. But all is covered in the documentation.
You will need a order field in your model:
class Song(models.Model):
title = models.CharField(max_length=65)
more_info = models.CharField(max_length=255)
#todo: foreignkey to User
order = models.PositiveIntegerField()
class Meta:
order_by = ['order']
# to ensure database integrity
unique_thogeter = [(user, order)]
you may also need to update your create view,
class SongListCreate(CreateView):
model = Song
def get_context_data(self, *args, **kwargs):
context = super(SongListCreate, self).get_context_data(*args, **kwargs)
# add a song formset to the context
# or a bound formset from validation
return context
def form_valid(self, form):
formset = SongFormset(#post data)
objects = formset.save(commit = False)
objects.update(#user instance,
#and other data you might need like the new orders)
objects.save()
return super(SongListCreate, self).form_valid(form)
This is roughly what you may need to do, working with formsets is quite a bit hard while you get used to.
You may also want to use a custom library to manage the order of the songs easily, like moving up or down, something like django-positions.
Regards.