My models.py looks like following:
class Exercise(models.Model):
#Field for storing exercise type
EXERCISE_TYPE_CHOICES = (
(1, 'Best stretch'),
(2, 'Butterfly reverse'),
(3, 'Squat row'),
(4, 'Plank'),
(5, 'Push up'),
(6, 'Side plank'),
(7, 'Squat'),
)
exercise_type = models.IntegerField(choices=EXERCISE_TYPE_CHOICES)
#Field for storing exercise name
-- Here comes the logic --
#Field for storing intensity level
INTENSITY_LEVEL_CHOICES = (
(1, 'Really simple'),
(2, 'Rather Simple'),
(3, 'Simple'),
(4, 'Okay'),
(5, 'Difficult'),
(6, 'Rather Difficult'),
(7, 'Really Difficult'),
)
intensity_level = models.IntegerField(choices=INTENSITY_LEVEL_CHOICES)
#Field for storing video url for a particular exercise
video_url = models.URLField()
#Field for storing description of the exercise
description = models.CharField(max_length=500)
I want to have a field called 'exercise_name' for Class Exercise, but in the following way:
For exercise_type=1 it should be 'Best stretch'
For exercise_type=1 it should be 'Butterfly reverse' and so on.
How can I achieve this? Or if not this way, is there a better way to do this?
Bottom line: My Exercise should have following fields- Type, Name, Description, Video_url
If you want to get string representation based on exercise_type, simply use get_exercise_type_display(). It will returns based on EXERCISE_TYPE_CHOICES.
ex = Exercise(exercise_type=1, intensity_level=1)
ex.get_exercise_type_display() # => 'Best stretch'
ex.get_intensity_level_display() # => 'Really simple'
Related
The choice field required in django is in the following format
new_choices = (
(1, 'Data 1'),
(2, 'Data 2'),
(3, 'Data 3'),
(4, 'Data 4'),
(5, 'Data 5'),
(6, 'Data 6'),
(7, 'Data 7'),
)
I am trying to get the data from db but the data is not getting properly
CHOICES = heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1)
test =([('(' + str(p.head) + '-' + p.detail + ')') for p in CHOICES])
len_of_test = len(test)
new_choices =[]
for n in range(len_of_test):
new_choices = '(' + str(n) + "," + test[n] + ')'
The output I am getting from the above code is
new_choices = ['(0,(Data 0))','(1,(Data 1))','(2,(Data 2))',...]
need to get the output as below
new_choices = (
(1, 'Data 1'),
(2, 'Data 2'),
(3, 'Data 3'),
(4, 'Data 4'),
(5, 'Data 5'),
(6, 'Data 6'),
(7, 'Data 7'),
)
You can construct a list of 2-tuples with:
CHOICES = heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1)
new_choices = [
(i, f'{p.head}-{p.detail}')
for i, p in enumerate(CHOICES, 1)
]
But populating data from a QuerySet often is not necessary. Usually a ModelChoiceField is used to pick an element for a ForeignKey.
That being said, you probably are looking for a ModelChoiceField [Django-doc] which is a ChoiceField populated by a queryset.
As Willem Van Onsem notes in a comment, you should probably use database IDs instead of 0,1,... as the keys in the list of choices.
I would use an approach like the following:
qs = heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1)
new_choices = []
for p in qs:
label = '(' + str(p.head) + '-' + p.detail + ')'
new_choices.append((p.id, label))
I am quite new to Python and I need your professional advice.
What I want in the end is, that I get the lenght of the injury_list per player. The players are stored in PlayerLinks
playerLinks = ['https://www.transfermarkt.de/Serge Gnabry/verletzungen/spieler/159471',
'https://www.transfermarkt.de/Jamal Musiala/verletzungen/spieler/580195',
'https://www.transfermarkt.de/Douglas Costa/verletzungen/spieler/75615',
'https://www.transfermarkt.de/Joshua Kimmich/verletzungen/spieler/161056',
'https://www.transfermarkt.de/Alexander Nübel/verletzungen/spieler/195778',
'https://www.transfermarkt.de/Kingsley Coman/verletzungen/spieler/243714',
'https://www.transfermarkt.de/Christopher Scott/verletzungen/spieler/503162',
'https://www.transfermarkt.de/Corentin Tolisso/verletzungen/spieler/190393',
'https://www.transfermarkt.de/Leon Goretzka/verletzungen/spieler/153084',
'https://www.transfermarkt.de/Javi Martínez/verletzungen/spieler/44017',
'https://www.transfermarkt.de/Tiago Dantas/verletzungen/spieler/429987',
'https://www.transfermarkt.de/Robert Lewandowski/verletzungen/spieler/38253',
'https://www.transfermarkt.de/Lucas Hernández/verletzungen/spieler/281963',
'https://www.transfermarkt.de/Josip Stanisic/verletzungen/spieler/483046',
'https://www.transfermarkt.de/Thomas Müller/verletzungen/spieler/58358',
'https://www.transfermarkt.de/Benjamin Pavard/verletzungen/spieler/353366',
'https://www.transfermarkt.de/Bouna Sarr/verletzungen/spieler/190685',
'https://www.transfermarkt.de/Leroy Sané/verletzungen/spieler/192565',
'https://www.transfermarkt.de/Manuel Neuer/verletzungen/spieler/17259',
'https://www.transfermarkt.de/David Alaba/verletzungen/spieler/59016',
'https://www.transfermarkt.de/Niklas Süle/verletzungen/spieler/166601',
'https://www.transfermarkt.de/Tanguy Nianzou/verletzungen/spieler/538996',
'https://www.transfermarkt.de/Ron-Thorben Hoffmann/verletzungen/spieler/317444',
'https://www.transfermarkt.de/Jérôme Boateng/verletzungen/spieler/26485',
'https://www.transfermarkt.de/Alphonso Davies/verletzungen/spieler/424204',
'https://www.transfermarkt.de/Eric Maxim Choupo-Moting/verletzungen/spieler/45660',
'https://www.transfermarkt.de/Marc Roca/verletzungen/spieler/336869']
injury_list = []
name_list = []
With the code below I get a list of all injuries of all playersLinks.
However, the lists are not from equal size. And I need the name of each player next to the injuries of that specific player.
I tried the following:
However, the lenght of injury_list is a random numebr then and not the number per player.
How do I get instead the lenght of the injury_list by player?
In order that I have the correct names next to the injuries.
for p in range(len(playerLinks)):
page = playerLinks[p]
response = requests.get(page, headers={'User-Agent': 'Custom5'})
print(response.status_code)
injury_data = response.text
soup = BeautifulSoup(injury_data, 'html.parser')
table = soup.find(id="yw1")
injurytypes = table.select("td[class='hauptlink']")
for j in range(len(injurytypes)):
all_injuries = [injury.text for injury in injurytypes]
injury_list.extend(all_injuries)
image = soup.find("div", {"class": "dataBild"})
for j in range(len(image)):
names = image.find("img").get("title")
name_list.append(''.join(names))
name_list_def = name_list * len(injury_list)
Through the img tag I get the names of the players.
Do you have any advice?
Thanks a lot!
player_inj_numb=[]
for url in (playerLinks):
player_name = url.split('/')[3]
response = requests.get(url, headers={'User-Agent': 'Custom5'})
print(response.status_code)
injury_data = response.text
soup = BeautifulSoup(injury_data, 'html.parser')
table = soup.find(id="yw1")
nbInjury = len(table.findAll("tr"))
player_inj_numb.append((player_name,nbInjury-1))
print(player_inj_numb)
which outputs:
[('Serge Gnabry', 15), ('Jamal Musiala', 0), ('Douglas Costa', 15), ('Joshua Kimmich', 12), ('Alexander Nübel', 2), ('Kingsley Coman', 15), ('Christopher Scott', 0), ('Corentin Tolisso', 14), ('Leon Goretzka', 15), ('Javi Martínez', 15), ('Tiago Dantas', 0), ('Robert Lewandowski', 15), ('Lucas Hernández', 15), ('Josip Stanisic', 8), ('Thomas Müller', 13), ('Benjamin Pavard', 9), ('Bouna Sarr', 8), ('Leroy Sané', 11), ('Manuel Neuer', 15), ('David Alaba', 15), ('Niklas Süle', 13), ('Tanguy Nianzou', 4), ('Ron-Thorben Hoffmann', 4), ('Jérôme Boateng', 15), ('Alphonso Davies', 3), ('Eric Maxim Choupo-Moting', 15), ('Marc Roca', 7)]
I got the name from the url, since it is already there, no need for additional scraping.
The number of injurys is equal the number of row in the table minus the first row which is the table header.
Please note that some player have more than 15 injurys so you will need to get the subsequent page in those cases.
I want to collect the places around my city, Pekanbaru, with latlong (0.507068, 101.447777) and I will convert it to the dataset. Dataset (it contains place_name, place_id, lat, long and type columns).
Below is the script that I tried.
import json
import urllib.request as url_req
import time
import pandas as pd
NATAL_CENTER = (0.507068,101.447777)
API_KEY = 'API'
API_NEARBY_SEARCH_URL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
RADIUS = 30000
PLACES_TYPES = [('airport', 1), ('bank', 2)] ## TESTING
# PLACES_TYPES = [('airport', 1), ('bank', 2), ('bar', 3), ('beauty_salon', 3), ('book_store', 1), ('cafe', 1), ('church', 3), ('doctor', 3), ('dentist', 2), ('gym', 3), ('hair_care', 3), ('hospital', 2), ('pharmacy', 3), ('pet_store', 1), ('night_club', 2), ('movie_theater', 1), ('school', 3), ('shopping_mall', 1), ('supermarket', 3), ('store', 3)]
def request_api(url):
response = url_req.urlopen(url)
json_raw = response.read()
json_data = json.loads(json_raw)
return json_data
def get_places(types, pages):
location = str(NATAL_CENTER[0]) + "," + str(NATAL_CENTER[1])
mounted_url = ('%s'
'?location=%s'
'&radius=%s'
'&type=%s'
'&key=%s') % (API_NEARBY_SEARCH_URL, location, RADIUS, types, API_KEY)
results = []
next_page_token = None
if pages == None: pages = 1
for num_page in range(pages):
if num_page == 0:
api_response = request_api(mounted_url)
results = results + api_response['results']
else:
page_url = ('%s'
'?key=%s'
'&pagetoken=%s') % (API_NEARBY_SEARCH_URL, API_KEY, next_page_token)
api_response = request_api(str(page_url))
results += api_response['results']
if 'next_page_token' in api_response:
next_page_token = api_response['next_page_token']
else: break
time.sleep(1)
return results
def parse_place_to_list(place, type_name):
# Using name, place_id, lat, lng, rating, type_name
return [
place['name'],
place['place_id'],
place['geometry']['location']['lat'],
place['geometry']['location']['lng'],
type_name
]
def mount_dataset():
data = []
for place_type in PLACES_TYPES:
type_name = place_type[0]
type_pages = place_type[1]
print("Getting into " + type_name)
result = get_places(type_name, type_pages)
result_parsed = list(map(lambda x: parse_place_to_list(x, type_name), result))
data += result_parsed
dataframe = pd.DataFrame(data, columns=['place_name', 'place_id', 'lat', 'lng', 'type'])
dataframe.to_csv('places.csv')
mount_dataset()
But the script returned with Empty DataFrame.
How to solve and got the right Dataset?
I am afraid the scraping of the data and storing it is prohibited by the Terms of Service of Google Maps Platform.
Have a look at the Terms of Service prior to advance with the implementation. The paragraph 3.2.4 'Restrictions Against Misusing the Services' reads
(a) No Scraping. Customer will not extract, export, or otherwise scrape Google Maps Content for use outside the Services. For example, Customer will not: (i) pre-fetch, index, store, reshare, or rehost Google Maps Content outside the services; (ii) bulk download Google Maps tiles, Street View images, geocodes, directions, distance matrix results, roads information, places information, elevation values, and time zone details; (iii) copy and save business names, addresses, or user reviews; or (iv) use Google Maps Content with text-to-speech services.
source: https://cloud.google.com/maps-platform/terms/#3-license
Sorry to be bearer of bad news.
I'm trying to migrate my app to the database, but the error does not allow me
Where I should make changes?
I have already looked through other Decisions. Nothing could help me
class Movie(models.Model):
NON_RATED = 0
RATED_G = 1
RATED_PG = 2
RATED_R = 3
RATINGS = (
(0, 'NR-not_rated'),
(1, 'G-General_Audiences'),
(2, 'PG-Parental_Guidances', 'Suggested'),
(3, 'R-Restricted')
)
rating = models.IntegerField(
choices=RATINGS,
default=0)
Choices attribute takes a list or tuple of 2 pairs. You cannot have a third value as you have.
class Movie(models.Model):
NON_RATED = 0
RATED_G = 1
RATED_PG = 2
RATED_R = 3
RATINGS = (
(0, 'NR-not_rated'),
(1, 'G-General_Audiences'),
(2, 'PG-Parental_Guidances', 'Suggested'), # you should remove Suggested here.
(3, 'R-Restricted')
)
rating = models.IntegerField(
choices=RATINGS,
default=0)
If you want another one you can try (2, ('PG-Parental_Guidances', 'Suggested')) but this will also give an error in some default values because of the internal structure.
I've got two models like these:
class Schedule(models.Model):
name = models.CharField(_('name'), blank=True, max_length=15)
class Day(models.Model):
DAYS_OF_THE_WEEK = (
(0, _('Monday')),
(1, _('Tuesday')),
(2, _('Wednesday')),
(3, _('Thursday')),
(4, _('Friday')),
(5, _('Saturday')),
(6, _('Sunday')),
)
schedule = models.ForeignKey(Schedule, blank=True, null=True, verbose_name=_('schedule'))
day = models.SmallIntegerField(_('day'), choices=DAYS_OF_THE_WEEK)
opening = models.TimeField(_('opening'), blank=True)
closing = models.TimeField(_('closing'), blank=True)
It's possible that a schedule can have two Day objects like so:
Day(schedule=1, day=0, opening=datetime.time(7, 30), closing=datetime.time(10, 30))
Day(schedule=1, day=0, opening=datetime.time(12, 30), closing=datetime.time(15, 30))
like different shifts on the same day.
If I iterate them now i'll get two entries of day 0, like so
[day for day in schedule]
[0, 0, 1, 2, 3, 4, 5, 6]
How can I create a queryset so it'll group same days together and keep their attributes?
[day for day in schedule]
[0 (two entries), 1, 3, 4, 5, 6]
Maybe something like
[id: [day], id: [day]]
The code I ended up using is this:
from itertools import groupby
day_set = store.schedule_set.all()[0].day_set.all()
schedule = dict()
for k, v in groupby(day_set, lambda x: x.day):
schedule[k] = list(v)
and sending schedule to the template for rendering, which works like a charm.
You can group them at template level, using {% regroup %} or {% for %}-loop with {% ifchanged %} tag.
In Python code use groupby.