One thing I found frustrating in Django is the seemingly required asymmetry when defining many-to-many relationships. I teach Django and would really like to find the "most elegant" way to describe and teach many-to-many relationships in Django.
One of my students used the technique of putting the class name in as a string in making her many-to-many model. This allows her to avoid less-than-intuitive techniques like related-name. This is my simplified version of her model - the key is that Person and Course are strings, not class names.
class Person(models.Model):
email = models.CharField(max_length=128, unique=True)
courses = models.ManyToManyField('Course', through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
class Course(models.Model):
title = models.CharField(max_length=128, unique=True)
members = models.ManyToManyField('Person', through='Membership')
But while this looks pretty to me, I am concerned that I have messed things up. I have done some basic testing and see no downsides to this style of model definition, but I am concerned that I messed something up that I don't even understand. So I submit this as a question, "What is wrong with this picture?"
There's nothing unusual or controversial about using strings to define a relationship field; this is fully documented. But it doesn't have anything to do with making the relationship symmetrical.
I'm not clear why your student has defined the relationship twice. That seems unnecessary, as does the use of an explicit through table. Your definition is exactly equivalent to this much simpler one:
class Person(models.Model):
email = models.CharField(max_length=128, unique=True)
courses = models.ManyToManyField('Course', related_name='members')
class Course(models.Model):
title = models.CharField(max_length=128, unique=True)
Note there is no need to define anything on Course, and no need for an explicit through table - which, even if it has no extra fields, disables some functionality like inline admin forms. Given a Course object, you can do my_course.members.all() to get the members just as in your version.
Related
I am not getting why people write foreign key in two way and what is the purpose of this? are they both same or any different?
I notice some people write like:
author = models.ForeignKey(Author, on_delete=models.CASCADE)
and some people write it like:
author = models.ForeignKey('Author', on_delete=models.CASCADE)
What is different between these? is there any special purpose of writing like this or they both are same?
What is different between these? is there any special purpose of writing like this or they both are same?
They both result in the same link yes. The string will later be "resolved", and eventually the ForeignKey will point to the Author model.
Using strings however is sometimes the only way to make references however, if the models to which you target need to be defined yet. For example in the case of a cyclic reference.
Imagine for example that you define relations like:
class Author(models.Model):
name = models.CharField(max_length=128)
favorite_book = models.ForeignKey(Book, null=True, on_delete=models.SET_NULL)
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Here a Book refers to an Author, and an Author refers to a Book. But since the Book class is not constructed at the time you construct the ForeignKey, this will give a NameError.
We can not define the Author after we defined the Book, since then we refer to the Author before it is constructed (and this thus will again yield a NameError).
We can however use strings here, th avoid the circular reference, like:
class Author(models.Model):
name = models.CharField(max_length=128)
favorite_book = models.ForeignKey('Book', null=True, on_delete=models.SET_NULL)
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
By using a string, it is fine for the Python interpreter, since you do not use an identifier that is not yet defined, and Django will then, when the models are loaded, replace the strings with a reference to the corresponding model.
The documentation on a ForeignKey [Django-doc]:
If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself (...)
If the model is defined in another app, then you can refer to it with app_name.ModelName.
Say you have laid your models out like this:
models/
__init__.py
model_a.py
model_b.py
This is a common layout when you have an app with a lot of models and you want to better organize your code. Now say ModelA has a foreign key to ModelB and ModelB has a foreign key to ModelA. You cannot have both files importing the other model because you would have a circular import.
Referencing another model by string allows you to "lazily" reference another model that it has not yet loaded, this solves the problem of having circular imports
First of all I have to admit that I'm quite new to all this coding stuff but as I couldn't find a proper solution doing it myself and learning to code is probably the best way.
Anyway, I'm trying to build an app to show different titleholders, championships and stuff like that. After reading the Django documentation I figured out I have to use intermediate models as a better way. My old models.py looks like this:
class Person(models.Model):
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
[...]
class Team(models.Model):
name = models.CharField(max_length=64)
team_member_one = models.ForeignKey(Person)
team_member_two = models.ForeignKey(Person)
class Championship(models.Model):
name = models.CharField(max_length=128)
status = models.BooleanField(default=True)
class Titleholder(models.Model):
championship = models.ForeignKey(Championship)
date_won = models.DateField(null=True,blank=True)
date_lost = models.DateField(null=True,blank=True)
titleholder_one = models.ForeignKey(Person,related_name='titleholder_one',null=True,blank=True)
titleholder_two = models.ForeignKey(Person,related_name='titleholder_two',null=True,blank=True)
Championships can be won by either individuals or teams, depending if it's a singles or team championship, that's why I had to foreign keys in the Titleholder class. Looking at the Django documentation this just seems false. On the other hand, for me as a beginner, the intermediate model in the example just doesn't seem to fit my model in any way.
Long story short: can anyone point me in the right direction on how to build the model the right way? Note: this is merely a question on how to build the models and displaying it in the Django admin, I don't even talk about building the templates as of now.
Help would be greatly appreciated! Thanks in advance guys.
So I will take it up from scratch. You seem to be somewhat new to E-R Database Modelling. If I was trying to do what you do, I would create my models the following way.
Firstly, Team would've been my "corner" model (I use this term to mean models that do not have any FK fields), and then Person model would come into play as follows.
class Team(models.Model):
name = models.CharField(max_length=64)
class Person(models.Model):
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
team = models.ForeignKey(to=Team, null=True, blank=True, related_name='members')
This effectively makes the models scalable, and even if you are never going to have more than two people in a team, this is good practice.
Next comes the Championship model. I would connect this model directly with the Person model as a many-to-many relationship with a 'through' model as follows.
class Championship(models.Model):
name = models.CharField(max_length=64)
status = models.BooleanField(default=False) # This is not a great name for a field. I think should be more meaningful.
winners = models.ManyToManyField(to=Person, related_name='championships', through='Title')
class Title(models.Model):
championship = models.ForeignKey(to=Championship, related_name='titles')
winner = models.ForeignKey(to=Person, related_name='titles')
date = models.DateField(null=True, blank=True)
This is just the way I would've done it, based on what I understood. I am sure I did not understand everything that you're trying to do. As my understanding changes, I might modify these models to suit my need.
Another approach that can be taken is by using a GenericForeignKey field to create a field that could be a FK to either the Team model or the Person model. Or another thing that can be changed could be you adding another model to hold details of each time a championship has been held. There are many ways to go about it, and no one correct way.
Let me know if you have any questions, or anything I haven't dealt with. I will try and modify the answer as per the need.
I've attempted to add a second ForeignKey relationship to a Django Model which relates to a model which hasn't yet been created.
class Forms2012(models.Model):
"""
Employer forms for the 2012-13 tax year
"""
employer = models.ForeignKey('Employer', blank=True, null=True)
# employee model is yet to be implemented
employee = models.ForeignKey('Employee', blank=True, null=True)
name = models.CharField(
max_length=50,
choices=constants.FORM_CHOICES)
description = models.CharField(max_length=255)
datemodified = models.DateTimeField()
As you might expect this is giving a not installed or is abstract error. However I've been told it should be possible to validate this because that key is optional.
Could someone explain if this is possible, I've added the flags blank=True, null=True to the FK but model validation fails so I think I'm fighting a losing battle.
Why don't you make (temporary) dummy models?
I would recommend that you implement a "stub" Employee model eg
class Employee(models.Model):
pass
If you are using database migrations ( eg South ), which you should, it should be a simple matter to "fill out" the Employee class later on.
However, if you want a fairly involved "solution" to the problem, you can have a look at the accepted answer in this question. The author of the question & answer admits that it is ugly ( even though it works ). The "stub" solution is better.
suppose the following simple models:
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
author = models.ForeignKey(User, related_name='author_set')
How can I get all the authors that participated in a particular blog (i.e. pk=1)? I tried something like this, but it didn't work.
User.objects.author_set.filter(blog=Blog.objects.get(pk=1))
Many thanks in advance!
User.objects.filter(author_set__blog__pk=1)
I wasn't paying attention to your related name, so the code above (revised) now uses the proper related name. However, this is a really bad related name. The related name should describe what's on the opposite side, i.e. Entry. So really it should be related_name='entry_set'. However, that's the default anyways, so you can remove related_name if you just want that. I would typically use a simple pluralized version of the related class, which would be in this case related_name='entries'. Or, you might want to use something like "blog_entries" to be more specific.
I've previously asked questions for this project, regarding the Django Admin, Inlines, Generics, etc. Thanks again to the people who contributed answers to those. For background, those questions are here:
Django - Designing Model Relationships - Admin interface and Inline
Django Generic Relations with Django Admin
However, I think I should probably review my model again, to make sure it's actually "correct". So the focus here is on database design, I guess.
We have a Django app with several objects - Users (who have a User Profile), Hospitals, Departments, Institutions (i.e. Education Institutions) - all of whom have multiple addresses (or no addresses). It's quite likely many of these will have multiple addresses.
It's also possible that multiple object may have the same address, but this is rare, and I'm happy to have duplication for those instances where it occurs.
Currently, the model is:
class Address(models.Model):
street_address = models.CharField(max_length=50)
suburb = models.CharField(max_length=20)
state = models.CharField(max_length=3, choices=AUSTRALIAN_STATES_CHOICES)
...
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
...
class Hospital(models.Model):
name = models.CharField(max_length=20)
address = generic.GenericRelation(Address)
...
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
address = generic.GenericRelation(Address)
...
Firstly - am I doing it right, with the FK field on each object that has address(es)?
Secondly, is there a better alternative to using Generic Relations for this case, where different objects all have addresses? In the other post, somebody mentioned using abstract classes - I thought of that, but there seems to be quite a bit of duplication there, since the addresses model is basically identical for all.
Also, we'll be heavily using the Django admin, so it has to work with that, preferrably also with address as inlines.(That's where I was hitting an issue - because I was using generic relationships, the Django admin was expecting something in the content_type and object_id fields, and was erroring out when those were empty, instead of giving some kind of lookup).
Cheers,
Victor
I think what you've done is more complicated than using some kind of subclassing (the base class can either be abstract or not).
class Addressable(models.Model):
... # common attributes to all addressable objects
class Hospital(Addressable):
name = models.CharField(max_length=20)
...
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
class Address(models.Model):
street_address = models.CharField(max_length=50)
suburb = models.CharField(max_length=20)
state = models.CharField(max_length=3, choices=AUSTRALIAN_STATES_CHOICES)
...
owner = models.ForeignKey(Addressable)
You should consider making the base class (Addressable) abstract, if you don't want a seperate table for it in your database.