Django - Get specific columns with get_object_or_404() - django

Is there a way to only get specific columns from the database using the get_object_or_404()?
This is my query for getting the thesis information from my database. But I only want to return the title , author, and published date instead of all the columns from that specific thesis.
details = get_object_or_404(thesisDB, slug=slug, published_status='Approved')

Related

Django and Postgres inserting into many-to-many table not working

I'm using python and psycopg2 to scrape some data and insert them into my database.
I've already created the movies and actors tables inside my Django models.py and inside my movies table, there is a many to many relationship between movies and actors table.
below is my models.py:
class Movie(models.Model):
name = models.CharField(max_length=55)
summary = models.TextField(max_length=1024)
actor = models.ManyToManyField(Actor, blank=True)
when I create a movie from Django-admin I select which actors are included in the movie and everything works fine and all the related actors for that movie will show up on my website.
But the problem is that when I try to insert scraped data into my database outside of my Django project folder, the related actors won't be shown on my website because obviously, I have not set the many to many relationship between them.
I have tried creating a junction table using SQL commands which gets the movie id and the actor's id and links them together but I don't know how I should tell Django to use that table and show the related actors for each movie.
This is the SQL code I use to insert into my db:
INSERT INTO movies(name, summary)
VALUES ('movie name', 'sth')
and the code to insert to actors table:
INSERT INTO actors(name, bio)
VALUES ('actorname', 'sth')
Both actors and movies table have auto generated id and I insert them insto the junction table using the code below:
INSERT INTO movie_actors (actor_id, movie_id)
VALUES (
(SELECT actor_id from actors where name='actor name'),
(SELECT movie_id from movie where name='movie name')
)
Am I doing it right?
I would really appreciate it if someone could help me with this.
Django automatically creates a table for many2many relationships. From docs:
ManyToManyField.through
Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use.
The most common use for this option is when you want to associate extra data with a many-to-many relationship.
So you must find the name of the table that django had already created.
Secondly, I suggest that you use django's ORM instead of raw queries so you don't have these kind of problems anymore.
Django automatically creates a through table for M2M relations, if you need you can specify custom through table. In your case I think there is no need of custom through table.
I using Django ORM instead of writing raw query.
INSERT INTO movies(name, summary) VALUES ('movie name', 'sth')
instead of tis raw query you can use the following ORM query:
movie = Movie.objects.create(name="movie name", summary="movie sammuary")
This will create a movie entry in the Movie table.
Next to create user entry you can use the following query:
actor = Actor.objects.create(name="actor name", bio="actor bio")
Now you created the entries in both the table, next you can establish the realtion, for that you have to use the following query:
movie.actor.add(actor)
Incase if you want to add multiple actors at the same time, you create multiple actors object and use following query:
movie.actor.add(actor1, actor2, actor2)
For more details you can check django's offical documentation

How to structure django models and query them with ease?

I am building a Django web App that will count the total number of persons entering and exiting a school library in a day, week and year and then save to DB.
The Web App uses a camera that is controlled by OpenCv to show live feed on frontend (I have successfully implemented this already).
My problem is:
How can I design and structure my models to store each data by day, week, month and year?
And how can I query them to display them on different Bar Charts using chart.js?
I haven't used chart.js before but I think I can answer the first part of your question.
Consider this model from one of my projects for a "post" that a user can make on my webapp.
class Post(models.Model):
slug = models.SlugField(unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=2200)
image = models.ImageField(upload_to=photo_path, blank=False, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
Using a "DateTimeField" (or alternatively a "DateField") you can pretty easily store timestamp information which can be filtered using standard python Date or DateTime object comparisons. In my example, I'm storing image files and text information.
For your case you could simply create a new "Person" model where each person is given a timestamp (and whatever other info you might want to store) and then using django querying you can count how many people match certain datetime parameters.
Note the Django Docs (https://docs.djangoproject.com/en/3.1/ref/models/querysets/) recommend :
Don't use len() on QuerySets if all you want to do is determine the number of records in the set. It's much more efficient to handle a count at the database level, using SQL's SELECT COUNT(*), and Django provides a count() method for precisely this reason.
An example of how I'd approach your problem would be:
Models:
class Person(HabitModel):
timestamp = models.DateTimeField(auto_now_add=True)
#whatever extra data you want on each person walking by
#staticmethod
def get_number_of_people(start_timestamp, end_timestamp):
return Person.objects.filter(timestamp__gte=start_timestamp, timestamp__lt=end_timestamp)).count()
(Note the "__gte" and "__lt" are built-in for Django querying and imply [start_timestamp, end_timestamp) inclusive start time and exclusive endtime)
Now you should be able to store your data rather simply and quantify how many people objects were created in whatever timeframe you'd like!

Django search on date field with MySQL DB

I have a date field in one of my models. I want to develop a search service, which in user sends a query param as search key, for example '?search=2018' and the response would be all rows in data base that their date's year is 2018. Or if the user sent '?search=11' the response would be all rows that either their date's month is 11, or their date's day is 11.
I am using django 2 and MariaDB version 10.3.18
Here's my model:
class MyDate(models.Model):
name = models.CharField(max_length=255)
date = models.DateField()
From a controller and http request point of view, you cannot use the same parameter for both condition. It would need, for instance, both a search_year and a search_month. They also can be combined together.
From a model and SQL query point of view, the Django documentation about retrieving records with filters might be of help. There is an exemple there about filtering by years.

how to get a value of a field in django

I'm currently working on a django app like IMDB.com that have a Media ( contains tvshows and movies ) model and an Episode model with a one-to-many relationship between them to display these episodes at the TvShow page.
I managed to be able to show the episodes of a tvshow inside the page with:
def tvshow(request, tvshow_title):
tvshow = get_object_or_404(Media, title=tvshow_title)
episodes = Episode.objects.all().filter(is_published=True, tvshow=tvshow)
context = {
'tvshow': tvshow,
'episodes': episodes
}
return render(request, 'media/tvshow.html', context)
and this worked perfectly fine but I also needed to display episodes based on season and this got me kinda confused how do I know how many seasons does a tv show have when there's no field for it in the Media model, but the Episode model had a season_number field, so I tried to get to query the last episode of a tv show based on the season_number:
latest_episode = Episode.objects.order_by('-season_number').filter(is_published=True, tvshow=tvshow)[:1]
and I managed to indeed get the episode but I don't know now how to get what is the number of the season in it.
I tried
seasons = latest_episode.season_number
and
seasons = latest_episode['season_number']
and neither of them worked. please tell me if there's a better way to do it and if this way is good let me know how to get the season_number. :)
Using [:1] returns a QuerySet, which is basically a list, and not a model instance (think of it as returning [EPISODE] instead of just EPISODE. This means that you dont have access to the episode's season_number attribute.
Try this:
latest_episode = Episode.objects.order_by('-season_number').filter(is_published=True, tvshow=tvshow).first()
and then you should be able to use latest_episode.season_number

Django Pivot Table Creation

Good Afternoon,
I am working on a Django App. I have created a model like below.
From that model I would like to create a view displaying such a table as below:
As you can see I would like to create rows per country name in the model database and I would like to give counts per specification.
I could create the table with the country names by adding a meta class to the model for the country field and then loop it with template injection. To do that I also created a view as below:
def sum(request):
country_list_unique = Project.objects.order_by().values('country_ordering').distinct()
return render(request, 'project/project_sum.html', {'sumup':country_list_unique})
However, I don't have much of an idea how can I count the different specifications per country in views.py and how to inject them into html with Django.
I would appreciate any help.
Thank you very much in advance.
You can easily get the data using https://github.com/martsberger/django-pivot