django-orm

Adding aggregate over filtered self-join field to Admin list_display

北慕城南 提交于 2019-12-11 13:44:41
问题 I would like to augment one of my model admins with an interesting value. Given a model like this: class Participant(models.Model): pass class Registration(models.Model): participant = models.ForeignKey(Participant) is_going = models.BooleanField(verbose_name='Is going') Now, I would like to show the number of other Registration s for this Participant where is_going is False . So, something akin to this SQL query: SELECT reg.*, COUNT(past.id) AS not_going_num FROM registrations AS reg,

Save list of records and fields into django model

╄→гoц情女王★ 提交于 2019-12-11 09:56:13
问题 I receive this list from my website admin: [['present', '2'],['present', '1'], ['study', '1'], ['study', '3'], ['present', '4'], ['study', '4'], The first option is actually the field name that needs to be edit in Rollcall model and the second option is the user ID. Now I want to save this list to the Rollcall model: #models.py class Rollcall(models.Model): student = models.ForeignKey(User) present = models.BooleanField(default=False) study = models.BooleanField(default=False) So I first

Django ORM - LEFT OUTER JOIN with two columns?

十年热恋 提交于 2019-12-11 09:03:27
问题 This is the relevant code: class Book(models.Model): name = models.CharField(max_length=50) class BookNote(models.Model): text = models.CharField(max_length=50) book = models.ForeignKey(Book) user = models.ForeignKey(settings.AUTH_USER_MODEL) class Meta: unique_together = [('book', 'user'), ] Now, for a specific user in the website: I want to query all the books (all the table). And, For each book object, If the user has a BookNote for the book - get it, otherwise booknote should be null.

Restricting single Rating on each Book by each User : Django ORM

眉间皱痕 提交于 2019-12-11 08:12:28
问题 Edited Title : Limit multiple "Many to One" fields into "One to One" association : Django We've Book , User and Rating as Django model. Each Book has many Ratings Each Rating has one Book Each User has many Ratings Each Rating has one User For Book class Book(models.Model): isbn = models.CharField(max_length=32) title = models.CharField(max_length=256) def __str__(self): return self.title For Book Rating class BookRating(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE)

query for values based on date w/ Django ORM

本秂侑毒 提交于 2019-12-11 07:46:02
问题 I have a bunch of objects that have a value and a date field: obj1 = Obj(date='2009-8-20', value=10) obj2 = Obj(date='2009-8-21', value=15) obj3 = Obj(date='2009-8-23', value=8) I want this returned: [10, 15, 0, 8] or better yet, an aggregate of the total up to that point: [10, 25, 25, 33] I would be best to get this data directly from the database, but otherwise I can do the totaling pretty easily with a forloop. I'm using Django's ORM and also Postgres edit: Just to note, that my example

Django DB transactions and deadlocks

三世轮回 提交于 2019-12-11 07:37:17
问题 When running Django with Gunicorn with multiple processes/workers I'm getting a deadlock issue with some of my manual MySQL database transactions. DatabaseError(1205, 'Lock wait timeout exceeded; try restarting transaction') My setup uses multiple databases, and my function needs to be passed the database to use when it's called. For this reason, I can't use the standard Django transaction decorators as the db needs to be hard-coded as an argument. I've inspected the decorator code to look at

How to Combine Date and Time Fields into DateTime Field in Django F Expression

孤街浪徒 提交于 2019-12-11 07:27:51
问题 I have to get the difference of two datetime fields but one is pure datetime field and other is a combination of date and time. I tried this one: qs = Foo.objects.filter( bar__baz_id=self.kwargs['baz_pk'], ) start_datetime = ExpressionWrapper((F('x__date') + F('x__start')), output_field=DateTimeField()) qs = qs.annotate(start_datetime=start_datetime) before_start_wrapper = ExpressionWrapper( F('start') - F('start_datetime'), # 'start' is datetime field on Foo, start_datetime is annotated

Prefetch object with multiple levels of reverse lookups

可紊 提交于 2019-12-11 07:27:14
问题 I'm on Django 1.7 and have been using the new Prefetch objects which are a great addition. However I seem to be stuck when I need to traverse back more than one relationship. Here is my code: product_types = self.get_queryset().select_related().prefetch_related( 'excise_category__exciseitem_set__unit', Prefetch( 'bevtank_set__package_set__checkout_set', queryset=CheckOut.objects.filter( create_date__lte=end_date, submission__isnull=True, exempt=False), to_attr='checkouts_due' ) ) ... for pt

Django ORM exclude fails

点点圈 提交于 2019-12-11 07:08:25
问题 I have some problems with my query - with filter() it's ok but with exclude() doesn't work. My models: class Dictionary(DateTimeModel): base_word = models.ForeignKey(BaseDictionary, related_name=_('dict_words')) word = models.CharField(max_length=64) version = models.ForeignKey(Version) class FrequencyData(DateTimeModel): word = models.ForeignKey(Dictionary, related_name=_('frequency_data')) count = models.BigIntegerField(null=True, blank=True) source = models.ForeignKey(Source, related_name=

Increasing a datetime field with queryset.update

倾然丶 夕夏残阳落幕 提交于 2019-12-11 07:06:44
问题 My model looks like this class MyModel(models.Model): end_time = DateTimeField() and this is what I'm trying to achieve: m=MyModel.objects.get(pk=1) m.end_time += timedelta(seconds=34) m.save() but I want to do it with update() to avoid race conditions: MyModel.objects.filter(pk=1).update(end_time=F('end_time')+timedelta(seconds=34)) but it doesn't work. Is this possible with the django ORM or is raw SQL the only option? 回答1: This is completely possible. Not sure if you're looking at a cached