I have a model "Booking" referencing to another model "Event" with a foreign key.
class Event(models.Model):
title = models.CharField(_("title"), max_length=100)
class Booking(models.Model):
user = models.ForeignKey('auth.User', ..., related_name='bookings')
event = models.ForeignKey('Event', ..., related_name='bookings')
I want to get all the events a user has booked in a set, to use it in a ListView.
I have managed to accomplish that by overwriting ListView's get_queryset method:
def get_queryset(self):
user_bookings = Booking.objects.filter(user=self.request.user)
events = Event.objects.filter(id__in=user_bookings.values('event_id'))
return events
But I am quite sure, that that is not a very efficient way of solving my problem, in terms of needed database queries.
I have thought about using "select_related" method, but I didn't figured out how I could benefit from that in my usecase.
My question is: How would you solve this? What is the most efficient way to do something like this?
You can do this in one line: Event.objects.filter(bookings__user=self.request.user)
Related
I have a model Article:
class Article(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))
class Meta:
unique_together = ('author', 'title')
The method get_sentinel_user:
def get_sentinel_user():
return get_user_model().objects.get_or_create(username='deleted')[0]
Thus, using on_delete=models.SET(get_sentinel_user), I save posts after deleting the author (if he agrees to this, I ask him in a separate form). And instead of a real author, I set a "stub"-user as the author for his posts.
In such a situation, there is a problem with the uniqueness condition. If two users had articles with the same title and then one of them was deleted, then an error will occur when trying to delete the second user. Accordingly, I would like this error to be absent. So that the uniqueness condition applies only to real users and their articles. I tried this:
class Meta:
constraints = [
models.UniqueConstraint(
name='unique_combiantion_article_name_and_author',
fields=['title', 'author'],
condition=~models.Q(author__username='deleted')
)
]
But then I made sure that this does not work, we cannot use author__username.
Right now I'm thinking about just overriding validate_unique method. But first I would like to ask for advice. Maybe there is some other solution for this problem.
Thanks for any help.
How do I check if there are any ManyToMany field objects related to my model object?
For example, I have a model:
class Category(models.Model):
related_categories = models.ManyToManyField('self', blank=True)
I want to do something only if there are related objects existing:
if example_category.related_categories:
do_something()
I tried to do example_category.related_categories, example_category.related_categories.all(), example_category.related_categories.all().exists(), example_category.related_categories.count(), but none of these works for me.
I have no any additional conditions to filter by.
Is there any easy way to check emptiness of this field?
you should use the .exists method:
related_categories = example_category.related_categories
if related_categories.exists():
# do something
I'm designing a new Django app and due to several possibilities, I'm not sure which would be the best, thus I'd like opinions, and hopefully improve what I got so far.
This question comes close but not quite. This one touches the flat/nested subject which is helpful, while still not answering the question.
There are many others on the same subject, and yet none tell me what I want to know.
Background
The models have each unique properties with some shared attributes, and I need to reference them in another model, optimally with a single entry point rather than having a field for each possible model.
I want to be able to do complex Django ORM queries involving the Base class and filter by SubClass when needed. E.g Event.objects.all() to return all events. I'm aware of Django model utils Inheritance Manager and intend to use it if possible.
Also, I'll be using django admin to create and manage the objects, so an easy integration is a must. I want to be able to create a new SubEvent directly, without having first to create a Event instance.
Example
To illustrate, let's say I have the following models for app A.
class Event(models.Model):
commom_field = models.BooleanField()
class Meta:
abstract = True
class SubEventA(Event):
email = models.EmailField(unique=True)
class SubEventB(Event):
title = models.TextField()
class SubEventC(Event):
number = models.IntegerField(default=10)
# and so on
And also an app B, where I want to be able to reference a event which can be of any type, like:
class OtherModel(models.Model):
event = models.ForeignKey('A.Event')
# This won't work, because `A.Event` is abstract.
Possible solutions
Use a GenericForeignKey.
# B.models.py
class OtherModel(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
event = GenericForeignKey('content_type', 'object_id')
What I don't like about this is that I'll lose the querying capabilities Django ORM has, and I might need to do additional fiddling to get it working on admin. Not sure, never dealt with this before
Flatten Event
I can bring it all up to the base class and have flags or checks outside the model definition, something like:
class Event(models.Model):
commom_field = models.BooleanField()
email = models.EmailField(blank=True)
title = models.TextField(blank=True)
number = models.IntegerField(default=10)
This might seem like the best idea at first, but of course there are other kind of fields, and that forces me to allow nulls/blanks for most of them (like the email field), losing the db level integrity check.
OneToOne relationships
Rather than abstract like on 1 or flatten on 2 it is possible to have a db table for each, where the models will look like:
class Event(models.Model):
commom_field = models.BooleanField()
class SubEventA(models.Model):
event = models.OneToOneField(Event)
email = models.EmailField(unique=True)
class SubEventB(models.Model):
event = models.OneToOneField(Event)
title = models.TextField(blank=True)
class SubEventC(models.Model):
event = models.OneToOneField(Event)
number = models.IntegerField(default=10)
So far it solved the two initial problems, but now when I get to the admin interface, I'll have to customize each form to create the base Event before saving a SubEvent instance.
Questions
Is there a better approach?
Can any of the choices I present be improved in any direction (ORM query, DB constraints, admin interface)?
I've pondered about both answers and came up with something based off of those suggestions. Thus I'm adding this answer of my own.
I've chosen to use django-polymorphic, quite nice tool suggested by #professorDante. Since this is a multi-table inheritance, #albar's answer is also somewhat correct.
tl;dr
django-polymorphic attends the 3 main requirements:
Allow django ORM querying style
Keep db level constraints by having a multi-table inheritance and one table for each sub class
Easy django admin integration
Longer version
Django-polymorphic allows me to query all different event instances from the base class, like:
# assuming the objects where previously created
>>> Event.objects.all()
[<SubEventA object>, <SubEventB object>, <SubEventC object>]
It also has great django admin integration, allowing seamless objects creation and editing.
The models using django-polymorphic would look like:
# A.models.py
from polymorphic import PolymorphicModel
class Event(PolymorphicModel):
commom_field = models.BooleanField()
# no longer abstract
class SubEventA(Event):
email = models.EmailField(unique=True)
class SubEventB(Event):
title = models.TextField()
class SubEventC(Event):
number = models.IntegerField(default=10)
# B.models.py
# it doesnt have to be polymorphic to reference polymorphic models
class OtherModel(models.Model):
event = models.ForeignKey('A.Event')
Besides, I can reference only the base model from another class and I can assign any of the subclasses directly, such as:
>>> sub_event_b = SubEventB.objects.create(title='what a lovely day')
>>> other_model = OtherModel()
>>> other_model.event = sub_event_b
My .2c on this. Not sure about your design in #3. Each SubEvent subclasses Event, and has a one-to-one to Event? Isn't that the same thing?
Your proposal on the Generic Key is exactly what it is designed for.
Another possibility - Polymorphism with Mixins. Use something like Django-polymorphic, so querying returns you the subclass you want. I use this all the time and its super useful. Then make Mixins for attributes that will be reused across many classes. So a simple example, making an email Mixin
class EmailMixin(models.Model):
email = models.EmailField(unique=True)
class Meta:
abstract = True
Then use it
class MySubEvent(EmailMixin, models.Model):
<do stuff>
This way you dont have redundant attributes on subclasses, as you would if they were all in the parent.
Why not a multi-table inheritance?
class Event(models.Model):
commom_field = models.BooleanField()
class SubEventA(Event):
email = models.EmailField(unique=True)
class SubEventB(Event):
title = models.TextField(blank=True)
class SubEventC(Event):
number = models.IntegerField(default=10)
I have a model
class EventArticle(models.Model):
event = models.ForeignKey(Event, related_name='article_event_commentary')
author = models.ForeignKey(Person)
and another model
class Event(models.Model):
attendies = models.ManyToManyField(Person, related_name="people")
How do I restrict an author to only objects that are also attendies?
Typically, the ForeignKey limit_choices_to argument is your friend in situations like this. (See https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to)
You could restrict the author to a list of users of have attended any event. However, even doing that is far from ideal:
# don't try this at home, this will be excruciatingly slow...
def author_options():
all_attendee_ids = []
for e in Event.objects.all():
for a in e.attendies.all():
all_attendee_ids.append(a.id)
return {'author': Person.objects.filter(id_in=set(all_attendee_ids)).id}
# requires Django 1.7+
class EventArticle(models.Model):
event = models.ForeignKey(Event, related_name='article_event_commentary')
author = models.ForeignKey(Person, limit_choices_to=author_options)
However, even though you didn't explicitly state it in your question, I suspect you want authors to be limited to a set of attendees from that particular event, i.e. the same event as specified in the EventArticle model's event field.
In which case, this brings about two problems which I don't believe can be solved cleanly:
you can't pass parameters (i.e. the event ID) when using limit_choices_to, and
until the EventArticle model has a value for event, you wouldn't know which event was in question.
As using limit_choices_to isn't going to work here, there probably isn't a way to fix this cleanly. You could add a method to your EventArticle model which will give you a list of potential authors like so...
class EventArticle(models.Model):
event = models.ForeignKey(Event, related_name='article_event_commentary')
author = models.ForeignKey(Person)
def author_options(self):
if self.event:
return self.event.attendies.all()
else:
return []
...but you will still need to do some legwork to make those options available to the UI so the user can select them. Without knowing more about your setup, I'd be guessing if I tried to answer that part.
You can override save() of EventArticle model to ensure it.
I have a Friendship model which looks like this:
from_user = ForeignKey(User, related_name='friends')
to_user = ForeignKey(User, related_name='friends_')
I have a manager to get all the Friendship models of a user:
def for_user(self, user):
return self.filter( Q(to_user=user) | Q(from_user=user) )
So now I would like to have a queryset with all the user objects that are friends. I thought of just writing a simple loop and add them to a list but then I lose the ability to write queries. For example for all the friends of a user I would like to filter/get one with a particular username.
The title of my question is a little generic so if anybody knows a better one feel free to change it.
User.objects.filter(Q(friends__to_user=someuser)|Q(friends___from_user=someuser))
No clue if that second Q() will actually work, but that's what you've decided to call the related field.