I have two models in my Django application. The first one is Journey and Second is Schedule.
The Schedule models has a foreign key of Journey model. the schema of these models is as follow.
class Journey(models.Model):
pass
class Schedule(models.Model):
journey=models.ForeignKey(Journey)
day=models.CharField(max_lenth=3, choices=days)
start_time=models.TimeField()
def __unicode__(self):
return self.day
What I want to do is that when I run query Journey.objects.all() it should return the journey in order_by(Schedule.start_time). Like Journey.objects.all().order_by(Schedule.journey)
is it possible in Django ORM or does this feature provided by django or i have to make a custom query to do it.
Guidance will be appreciable
You can try like this:
Journey.objects.all().order_by('schedule__journey')
The format for querying child model field/reverse lookup is like this:
ParentModel.objects.all().order_by('lowercase_child_modelname__fieldname)')
For details, check here: https://docs.djangoproject.com/en/1.7/topics/db/queries/#lookups-that-span-relationships
Related
working on a project, where i came to a small problem with QuerySets. (Look at the bottom to see a short diagram of my model structure.) I tried to query some information of a BLOG-Model starting from the Collection-Model. Now is it better to query first the Entrie-Model and find somehow the Collection to afterwards find the Blog-Model and add the information in the end to the Collection? Or is there a better / faster way to get information directly from the parent Model? Normaly it is easy if you just have 1:n->1:n Relations because you can easily follow the foreignkey, but this confuses me.
Here a short overview of my model structure:
<--------------- QUERY DIRECTION ----------------
(BLOG) --(1:N)--> (ENTRIE) <--(N:1)-- (COLLECTION)
BR, Felix
django's relations works both ways so if you need blog model from collection model you can directly query your Blog model so from your diagram:
class Blog:
entrie = models.ForeignKey(Entrie, on_delete=CASCADE)
class Entrie:
pass
class Collection:
entrie = models.ForeignKey(Entrie, on_delete=CASCADE)
so your query can be something like if you have not specified any related_name attributes on your models relation fields
Blog.objects.filter(entrie__collection={your_data})
I have a table called 'users' and 'location'. Users table has a foreign key that relates to location table. I have a users serializer to get the JSON. What would I do to get the hyperlinks for the users table using its primary key?
In django rest framework documentation, I couldn't find a solution. I tried using hyperlinkrelatedfield. But still I couldn't achieve this. Can someone help me in finding the solution?
Using rest-framework HyperlinkedRelatedField does not work because it was never built to expose the URL of the object being requested. Mainly because since the client already has the url of the user, why send it back again? Nevertheless you can achieve this by doing something like this.
class UserSerializer(serializers.ModelSerializer):
user_url = serializers.SerializerMethodField()
class Meta:
model = User
def get_label_location(self, obj):
return HyperlinkedRelatedField(view_name='user-detail',
read_only=True) \
.get_url(obj, view_name='label-detail',
request=self.context['request'], format=None)
Take note on a few things,
view-name param to the HyperlinkedRelatedField should be based on your url configuration
read-only has to be true since otherwise you'll have to specify the queryset. But since we have the object needed to generate the url we can ignore that.
I've set format param to None but you might want to set it based on your settings.
You can read up about SerializerMethodField here.
I have this project where, I need to fetch multiple objects from multiple models in a view. I could do that by for loop but I think I shouldn't hit database in each loop. Should I use prefetch_related. or Should I know some other way to retrieve them.
for example:
class A(models.Model):
title_name=models.CharField(...)
id=models.AutoField(pk=True)
class B(models.Model):
user=models.ForeignKey(User,models.ON_CASCADE=True)
user_status=models.CharField(...)
id=models.ForeignKey(A, models.ON_CASCADE=True)
I need to display user_status, user and associated title_name. I get multiple objects, select_related will not be useful. Any suggestions.
You need make this queryset:
B.objects.all().select_related('user', 'id')
This queryset will generate sql that join user and A data from db
Next, in the model B to make a property:
#property
def title_name(self):
return self.id.title_name
Finally you'll get queryset that makes one SQL request to database and returns all data you need.
By the way, I would rename attribute "id" in the model B to "a".
I am working in django, am planning a database for rides for users.
each User can be on multiple Rides (over time) and each Ride can have multiple Users (passengers) in it.
Also, for each Ride there has to be only one Driver (also a User) so I think I have a many-to many relationship between the Rides and Users tables for what user is on what ride, and also a One-To-Many relationship between the Rides's Driver_id and the User_id. right?
My questions are-
I saw in the django docs that I should put a many-to-many field in One of the models. Does it matter which one? and also, does it create a new table like rides_users?
and also, what is the difference (in One-To-many relationship) between using a foreignKey field and a OneToManyField field?
EDIT:
Currently, there are my models:
def get_image_path(models.Model):
return os.path.join('photos',str(instance.id),filename)
class UserProfile(models.Model):
user=models.OneToOneField(User)
phone_number=models.CharField(max_length=12)
profile_picture=models.ImageField(upload_to=get_image_path, black=True, null=True)
class Ride(models.Model):
driver=models.ForeignKey(UserProfile, related_name="r_driver")
destination=models.ForeignKey(Destination, related_name="r_final_destination")
leaving_time=models.DateTimeField()
num_of_spots=models.IntergerField()
passengers=models.ManyToMany(UserProfile, related_name="r_passengers")
mid_destinations=models.ManyToMany(Destination, related_name="r_mid_destinations")
class Destination(models.Model):
name=models.CharField(max_length=30)
As you can see, each Ride has multiple mid_destination and multiple passengers. a Ride also has One driver and One final destination.
The Issue is - when a User adds a Ride, I want the driver, destination and mid_destinations and the rest of the fields to be set by the User (the driver is user adding the Ride), Except for the passengers field. I want the other Users to add themselves to the ride, so when the Ride is created the User (driver) doesn't have to set the passengers.
How do I go about it? and also, any other suggestions about the models?
There is no such thing as a OneToManyField.
It doesn't matter from a practical point of view which side the ManyToManyField lives on. Personally, I'd put it on Ride, both to avoid changing the User model and because conceptually I'd say that rides are the main objects here.
And yes, adding the field will automatically create the linking table.
what you want is probably something like this
class MyModel(models.Model):
driver = models.ForeignKey(to=User, related_name='r_driver')
# you need to use a related name if you want to link to the same model more than once
passengers = models.ManyToManyField(User, related_name="r_passengers")
I'm trying to optimise my app by keeping the number of queries to a minimum... I've noticed I'm getting a lot of extra queries when doing something like this:
class Category(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=127, blank=False)
class Project(models.Model):
categories = models.ManyToMany(Category)
Then later, if I want to retrieve a project and all related categories, I have to do something like this :
{% for category in project.categories.all() %}
Whilst this does what I want it does so in two queries. I was wondering if there was a way of joining the M2M field so I could get the results I need with just one query? I tried this:
def category_list(self):
return self.join(list(self.category))
But it's not working.
Thanks!
Which, whilst does what I want, adds an extra query.
What do you mean by this? Do you want to pick up a Project and its categories using one query?
If you did mean this, then unfortunately there is no mechanism at present to do this without resorting to a custom SQL query. The select_related() mechanism used for foreign keys won't work here either. There is (was?) a Django ticket open for this but it has been closed as "wontfix" by the Django developers.
What you want is not seem to possible because,
In DBMS level, ManyToMany relatin is not possible, so an intermediate table is needed to join tables with ManyToMany relation.
On Django level, for your model definition, django creates an ectra table to create a ManyToMany connection, table is named using your two tables, in this example it will be something like *[app_name]_product_category*, and contains foreignkeys for your two database table.
So, you can not even acces to a field on the table with a manytomany connection via django with a such categories__name relation in your Model filter or get functions.