I have two models
class Customer(models.Model):
name = models.CharField(max_length=255, unique=True)
default_contact = models.ForeignKey("CustomerContact", verbose_name="...", related_name="default_contacts", null=True, on_delete=models.SET_NULL)
etc.
And
class CustomerContact(models.Model):
customer = models.ForeignKey(Customer, related_name='contacts')
user = models.OneToOneField(User, related_name='user_contacts', on_delete=models.SET_NULL)
address = models.ForeignKey(CustomerAddress, ....)
In this example Customer points to CustomerContact.
At the same time CustomerContact points to Customer.
My coworker says that pointing Customer points to CustomerContact violates the OneToMany nature of ForeignKey.
What am I doing wrong?
As I can see you want to have many CustomerContact related to one Customer, but Customer can also pick his favourite (or one can be set by manager). It's valid approach.
It can go both ways, as long as you will secure related_names properly.
default_contact = models.ForeignKey("CustomerContact", ... related_name="default_contacts") <= should be changed
default_contacts should be changed (i.e. to default_for_customers) because this name is for reversed relation, so actually for CustomerContact. It means, that you can use it in the following situation:
cc = CustomerContact.objects.get(id=1)
cc.default_for_customers.all() <= this will return QuerySet of Customer objects that is default for
It's simplier and less confusing.
Related
Good day.
I wish to annotate my model with information from a different table.
class CompetitionTeam(models.Model):
competition_id = models.ForeignKey('Competition', on_delete=models.CASCADE, to_field='id', db_column='competition_id')
team_id = models.ForeignKey('Team', on_delete=models.CASCADE, to_field='id', null=True, db_column='team_id')
...
class Team(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
teamleader_id = models.ForeignKey('User', on_delete=models.CASCADE, to_field='id', db_column='teamleader_id')
...
class Competition(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
...
Looping through my competitions, I wish to retrieve the list of competitionteam objects to be displayed with the relevant team's name. I tried:
CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=...)
-where instead of the ellipses I put Subquery expressions in. However, I'm unsure of how to match the team_id variable. eg.
*.anotate(name=Subquery(Team.objects.filter(id=competitionteam.team_id)).values('name'))
Related is the question: Django annotate field value from another model but I am unsure of how to implement that in this case. In that case, in place of mymodel_id, I used team_id but it only had parameters from the Team object, not my competition team object. I didn't really understand OuterRef but here is my attempt that failed:
CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=Subquery(Team.objects.get(id=OuterRef('team_id'))))
"Error: This queryset contains a reference to an outer query and may only be used in a subquery."
The solution for my question was:
CompetitionTeam.objects.filter(
competition_id=_competition.id,
team_id__in=joined_team_ids
).annotate(
name=Subquery(
Team.objects.filter(
id=OuterRef('team_id')
).values('name')
))
Thanks.
I'm currently working on a website (with Django), where people can write a story, which can be upvoted by themselves or by other people. Here are the classes for Profile, Story and Upvote:
class Profile(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30, null=True)
last_name = models.CharField(max_length=30, null=True)
class Story(models.Model):
author = models.ForeignKey('accounts.Profile', on_delete=models.CASCADE, related_name="author")
title = models.CharField(max_length=50)
content = models.TextField(max_length=10000)
class Upvote(models.Model):
profile = models.ForeignKey('accounts.Profile', on_delete=models.CASCADE, related_name="upvoter")
story = models.ForeignKey('Story', on_delete=models.CASCADE, related_name="upvoted_story")
upvote_time = models.DateTimeField(auto_now=True)
As you can see, Upvote uses two foreign keys to store the upvoter and the related story. Now I want to make a query which gives me all the stories, sorted by the amount of upvotes they have. I've tried my best to come up with some queries myself, but it's not exactly what I'm searching for.
This one doesn't work at all, since it just gives me all the stories in the order they were created, for some reason. Also it contains duplicates, although I want them to be grouped by story.
hot_feed = Upvote.objects.annotate(upvote_count=Count('story')).order_by('-upvote_count')
This one kind of works. But if I'm trying to access a partical story in my template, it just gives me back the id. So I'm not able to fetch the title, author and content from that id, since it's just an integer, and not an object.
hot_feed = Upvote.objects.values('story').annotate(upvote_count=Count('story')).order_by('-upvote_count')
Could someone help me out with finding the query I'm searching for?
You are querying from the wrong model, you here basically fetch Upvotes ordered by the number of stories, or something similar.
But your probaby want to retrieve Storys by the number of upvotes, so you need to use Story as "queryset root", and annotate it with the number of upvotes:
Story.objects.annotate(
upvote_count=Count('upvoted_story')
).order_by('-upvote_count')
I think the related_name of your story is however a bit "misleading". The related_name is the name of the relation "in reverse", so probably a better name is upvotes:
class Upvote(models.Model):
profile = models.ForeignKey(
'accounts.Profile',
on_delete=models.CASCADE,
related_name='upvotes'
)
story = models.ForeignKey(
'Story',
on_delete=models.CASCADE,
related_name='upvotes'
)
upvote_time = models.DateTimeField(auto_now=True)
In that case the query is:
Story.objects.annotate(
upvote_count=Count('upvotes')
).order_by('-upvote_count')
I have a model where basically i am Tracking users' activities. I want to know what is the page the user have accessed MOST.
Here are my modals.
class Visitor(models.Model):
session_key = models.CharField(max_length=40, primary_key=True)
user = models.ForeignKey(User, related_name='visit_history', null=True, editable=False)
....
class Pageview(models.Model):
visitor = models.ForeignKey(Visitor, related_name='pageviews')
url = models.CharField(max_length=500)
method = models.CharField(max_length=20, null=True)
view_time = models.DateTimeField()
Here is my query.
Pageview.objects.values('visitor__user__first_name', 'visitor__user__last_name', 'visitor__user').annotate(url_count=Count('url')).annotate(url_count_unique=Count('url', distinct=True))
Here i am getting users number of urls visited, and number of unique urls visited.
Here i also want to know which is the url user have visited the most?
EDIT
Translation of my query.
Goto PageViews and count the occurring of unique URLS.(how many times a url have occurred.) and give me the one that have most visited count against each user.
I hope the question is clear, if not let me know.
IMHO you're better off with a many-to-many relationship. You would have something like:
class VisitedURLs(models.Model):
page = models.ForeignKey(Visitor, ....)
user = models.ForeignKey(User, ....)
timestamp = models.DateTimeField(auto_now_add=True)
and the original models become something like:
class Visitor(models.Model):
members = models.ManyToManyField(PageView, through='VisitedURLs')
class PageView(models.Model):
url = models.CharField(max_length=500)
method = models.CharField(max_length=20, null=True)
In this case, you can use the count/distinct on the visitedURLs model and when you get an object of that type you'll have a FK to a Visitor object (which would give you the user...) and a FK to the URL.
Another way is to explicitly count each unique visitor/url combination and store it somewhere. Depending on usage (e.g. if you want to compute/display this often) you may be better off with the dedicated storage.
Here is the solution that i have come up with.
Pageview.objects.filter(visitor__user_id=user['visitor__user_id']).values(
'url').annotate(page_count=Count('id')).order_by('-page_count')
if max_visited_node:
user['max_visited_node'] = max_visited_node[0]
by this way i can get the count of the all the pages the user have visited. then i order them by that count and then i get the top first element which contains the URL and page_count.
This is what i was looking for. the suggestion of Laur lvan is worth considerable.
Trying to craft a relationship like so:
The combination of user/address can only have one rating, where an address is part of a building which is also a foreign key on the rating.
At the moment I have this:
class Rating(models.Model):
buildingaddress = select2.fields.ForeignKey(BuildingAddress, overlay='Select the Building Address')
building = select2.fields.ForeignKey(Building, db_column='bin', null=True, overlay='Select your Building')
author = select2.fields.ForeignKey(User, overlay='Select the Author')
suggestion = models.TextField()
rating = models.IntegerField(null=True, blank=True)
This doesn't work correctly at the moment, because it allows multiple ratings per user per address.
you can add a unique_together constraint to make it so every address and user combination has to be unique
https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together
unique_together = ('buildingaddress', 'author')
I've got Django tables like the following (I've removed non-essential fields):
class Person(models.Model):
nameidx = models.IntegerField(primary_key=True)
name = models.CharField(max_length=300, verbose_name="Name")
class Owner(models.Model):
id = models.IntegerField(primary_key=True)
nameidx = models.IntegerField(null=True, blank=True) # is Person.nameidx
structidx = models.IntegerField() # is PlaceRef.structidx
class PlaceRef(models.Model):
id = models.IntegerField(primary_key=True)
structidx = models.IntegerField() # used for many things and not equivalent to placeidx
placeidx = models.IntegerField(null=True, blank=True) # is Place.placeidx
class Place(models.Model):
placeidx = models.IntegerField(primary_key=True)
county = models.CharField(max_length=36, null=True, blank=True)
name = models.CharField(max_length=300)
My question is as follows. If in my views.py file, I have a Person referenced by name and I want to find out all the Places they own as a QuerySet, what should I do?
I can get this far:
person = Person.objects.get(name=name)
owned_relations = Owner.objects.filter(nameidx=nameidx)
How do I get from here to Place? Should I use database methods?
I'm also not sure if I should be using ForeignKey for e.g. Owner.nameidx.
Thanks and apologies for this extremely basic question. I'm not sure how to learn the basics of database queries except by trying, failing, asking SO, trying again... :)
The whole point of foreign keys is for uses like yours. If you already know that Owner.nameidx refers to a Person, why not make it a foreign key (or a OneToOne field) to the Person table? Not only do you get the advantage of referential integrity - it makes it impossible to enter a value for nameidx that isn't a valid Person - the Django ORM will give you the ability to 'follow' the relationships easily:
owned_places = Place.objects.filter(placeref__owner__person=my_person)
will give you all the places owned by my_person.
Incidentally, you don't need to define the separate primary key fields - Django will do it for you, and make them autoincrement fields, which is almost always what you want.
If u could redesign.Then
In owner nameidx can be a foreign key to Person(nameidx)
Placeref(structidx) could be a foreign key to Owner(structidx) and
Place(placeidx) could be a foreign key Place ref(placeidx)
Then u could deduce the place value easily..