Django: select data from 2 models - django

Good day!
I have 2 models and I am trying to get sql equivalent of : select * from both models where order=xx. Appreciate little assistance :)
class Orders(models.Model):
order_id = models.AutoField(primary_key=True)
created = models.DateTimeField(auto_now_add=True)
class ResourcePool(models.Model):
email = models.EmailField()
item_a = models.CharField()
item_b = models.CharField()
item_c = models.CharField()
order_id = models.ForeignKey(Orders)
Tried the following, but it does not inlude fields from 'Orders' model
ResourcePool.objects.filter(order_id__pk=26).values()
ResourcePool.objects.filter(order_id__pk=26).select_related().values()

ResourcePool.objects.filter(order_id__pk=26).values('orders__created','email','item_a',item_b','item_c')
try this

try this
order = Orders.objects.get(pk=26)
resource=ResourcePool.objects.filter(order_id=order.id).select_related()
And to obtain the data of "Orders"
id_order_pk26 = resource.order_id.order_id
created_pk26 = resource.order_id.created

Related

Query M2M relations in Django

I've the following model:
class Quiz(models.Model):
name = models.CharField(max_length=255)
month = models.DateField()
class Question(models.Model):
title = models.CharField(max_lenght=255)
category = models.CharField(max_length=255)
status = models.CharField(max_length=255, status=(('Pending', 'Pending'), ('Approved', 'Approved'))
class Contest(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
questions = models.ManyToManyField(Question, related_name='contest_questions')
Now I want to get list of quizes with all questions whose status=Pending?
Any help would be much appreciated!
Another approach is query directly from the M2M table using values_list():
quiz_ids = list(Contest.objects.filter(questions__status='Pending').values_list('quiz__id', flat=True))
quiz_query = Quiz.objects.filter(id__in=quiz_ids)

Django search for child models via foreign key

I have a models.py file that more or less looks like this:
class Match(models.Model):
match_id = models.BigIntegerField()
class Team(models.Model):
team_id = models.CharField(max_length=4)
match = models.ForeignKey(
Match,
related_name='teams',
on_delete=models.CASCADE,
)
win = models.BooleanField()
class Player(models.Model):
player_id = models.IntegerField()
team = models.ForeignKey(
Team,
related_name='players'
on_delete=models.CASCADE,
)
For each match, I want to find the two teams that played, and for each team, I want to find the players that were on the team. This is what I tried so far:
match_id = 123456789
match_info = Match_model.objects.get(match_id=match_id)
red_info = Team_model.objects.get(match=match_info, team_id='Red')
blue_info = Team_model.objects.get(match=match_info, team_id='Blue')
red_players = Player_model.objects.filter(team=red_info)
blue_players = Player_model.objects.filter(team=blue_info)
but Django is giving me the error:
Team matching query does not exist.
How would I go about fixing this error? Any pointers on how to correct my queries would be greatly appreciated!
try:
red_info = Team_model.objects.get(match=match_info, team_id='Red')
blue_info = Team_model.objects.get(match=match_info, team_id='Blue')
except Team_model.DoesNotExist:
pass
else:
red_players = Player_model.objects.filter(team=red_info)
blue_players = Player_model.objects.filter(team=blue_info)

How to represent join queries in Django?

How do we present sql query like this one in django?
select * from question LEFT JOIN (select * from question_solved where username = 'ashu'
) AS result on question.q_id = result.q_id
I tried to perform query separately,
q = question_solved.objects.filter(username='ashu')
y = Question.objects.filter(q__q_id = Question.q_id)
But it is giving me error
django.core.exceptions.FieldError: Cannot resolve keyword 'q' into field. Choices are: q_answer, q_content, q_id, q_submission, q_tags, q_title, q_type
my model file
from django.db import models
# Create your models here.
class Question(models.Model):
q_id = models.CharField(primary_key=True, max_length=20)
#q_difficulty = models.IntegerField()
q_title = models.CharField(max_length = 200)
q_content = models.CharField(max_length = 1000)
q_type = models.IntegerField()
q_answer = models.FloatField()
q_submission = models.IntegerField()
q_tags = models.CharField(max_length=10)
class Student(models.Model):
username = models.CharField(primary_key=True, max_length=30)
password = models.CharField(max_length=200)
class question_solved(models.Model):
q_id = models.CharField(primary_key=True, max_length=20)
username = models.CharField(max_length=30)
Query will produce result like this.
Thanks in advance.
You should use ForeignKey to relate models .
From what I understood you want to get all the questions solved by username ashu.
In your current state of models you can do this like:
First get a list of q_id values that are in the table for username ashu. you can do that using values_list():
quest=question_solved.objects.filter(username='ashu').values_list('q_id',flat=True)
Then from the Question table filter the objects with q_id in the list obtained from previous query.
solved_questions=Question.objects.filter(q_id__in=quest)
You can get all the question with all()
all_questions = Question.objects.all()
and if you want you can have 2 separate queryset one which is a list of question solved by 'ashuand other which is not solved byashu`.
unsolved_questions=Question.objects.exclude(q_id__in=quest).

How would I do this query in Django?

So let's say I have three models: User, CarBrand, CarModel, CarCharacteristics. The CarCharacteristics model describes how a user rates the characteristics of a car. So there can be many CarCharacteristics objects for a user, and a user can have many CarCharacteristics.
This is what my models look like:
class User(models.Model):
id = models.AutoField(primary_key=True)
class CarBrand(models.Model):
idcar_brand = models.AutoField(primary_key=True)
class CarModel(models.Model):
idcar_model = models.AutoField(primary_key=True)
car_brand = models.ForeignKey(CarBrand, null=True, on_delete=models.SET_NULL)
class CarCharacteristics(models.Model):
idcar_characteristics = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.PROTECT)
car_model = models.ForeignKey(CarModel, on_delete=models.PROTECT)
What I would like to do is to get all CarBrand objects where a User has a CarCharacteristics. This is what am I doing right now:
car_chars = CarCharacteristics.objects.filter(user=user_id)
car_brands_ids = []
for car_char in car_chars:
brand_id = car_char.car_model.car_brand.idcar_brand
if brand_id not in car_brands_ids:
car_brands_ids.append(brand_id)
brands = CarBrand.objects.filter(idcar_brand__in=brand_ids)
Is there a simpler way of doing this? And how do I get all the CarModels where there exists a CarCharacteristics?
Try this:
CarBrand.objects.exclude(carmodel__carcharacteristics__user=None).distinct()
I think I figured it out. I think this works:
user_id = request.user.pk
brands = CarBrand.objects.exclude(~Q(carmodel__carcharacteristics__user=user_id))
EDIT
Is what I have above also equivalent to this:
user_id = request.user.pk
car_models = CarModel.objects.filter(carcharacteristics__user=user_id)
brands = CarBrand.objects.filter(carmodel__in=car_models).distinct()
CarBrand.objects.filter(carmodel__carcharacteristics__user=request.user).distinct()

django sql join with like

I have following models
class Artist(models.Model):
name = models.CharField(max_length=200, unique=True)
photo = models.CharField(max_length=250)
views = models.IntegerField()
class Meta:
verbose_name = "artist"
ordering = ['-views']
def __unicode__(self):
return self.name
class Song(models.Model):
artist = models.ForeignKey("Artist")
name = models.CharField(max_length=250)
lyrics = models.TextField(max_length=255)
path = models.CharField(max_length=200)
views = models.IntegerField()
date = models.DateField()
class Meta:
verbose_name = "song"
ordering = ['-views']
def __unicode__(self):
return self.name
and would like to get all the rows that match the keyword.
I can do it in sql and returns what I want. here is the sql;
SELECT song.name, song.path FROM song JOIN artist on song.artist_id = artist.id WHERE artist.name LIKE %keyword% || song.name LIKE %keyword% || song.lyrics LIKE %keyword%
but could not figure out how to do that in django. should I use custom sql? do you guys have better idea?
thanks in advance
matching_songs = Song.objects.filter(Q(name__contains=keyword) | Q(lyrics__contains=keyword) | Q(artist__name__contains=keyword))
See Django docs on Q objects for more details
After 2 hours of digging and asking myself why I am not getting expected results, I realised that __contains is case-sensitive while __icontains is not.
So, for example if we have person named "torres" in database and supply "Torres" to __contains then it will return nothing while __icontains will return "Torres".