django-orm

In django, is there a way to directly annotate a query with a related object in single query?

本秂侑毒 提交于 2019-12-04 19:54:36
问题 Consider this query: query = Novel.objects.< ...some filtering... >.annotate( latest_chapter_id=Max("volume__chapter__id") ) Actually what I need is to annotate each Novel with its latest Chapter object, so after this query, I have to execute another query to select actual objects by annotated IDs. IMO this is ugly. Is there a way to combine them into a single query? 回答1: No, it's not possible to combine them into a single query. You can read the following blog post to find two workarounds.

Django GenericIPAddress field is not validating input

元气小坏坏 提交于 2019-12-04 18:48:10
Hi I have the following Django model class AccessPointIPAddress(models.Model): '''Model for storing AccessPoint IP Addresses.''' ap = models.ForeignKey(AccessPoint, related_name='ip_addresses') ip_address = models.GenericIPAddressField(protocol='IPv4') datetime = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['datetime'] get_latest_by = 'datetime' And I am assuming that django's GenericIPAddressField does some string validation that a string is indeed a valid IP Address. I also read django's source and it does have some validation functions tied to GenericIPAddressField But

Django: Custom Save method for Many-to-Many relation

柔情痞子 提交于 2019-12-04 16:59:30
I need to set custom save and delete methods on a Many-to-Many relation. I tried specifying a model with the "through" attribute but this over-complicated my code and introduced some problems. I don't need any extra field on the Many-to-Many model, just custom save and delete methods. Is it possible to accomplish this without specifying the "through" attribute? Here's code: class Order(BaseDate): #lots of fields relateds = models.ManyToManyField('RelatedProduct', verbose_name=_('related products'), blank=True, related_name='order_relateds', through='OrderRelateds') # more fields total =

How can I make a Django model read-only?

穿精又带淫゛_ 提交于 2019-12-04 16:18:35
问题 Is it possible to make a Django model read only? No creating, updating etc. N.B. this question is different to: Make a Django model read-only? (this question allows creation of new records) Whole model as read-only (only concerns the Django admin interface - I'd like the model to be read only throughout the whole app) 回答1: Override the save and delete methods for the model. How are you planning to add objects to your model? def save(self, *args, **kwargs): return def delete(self, *args, *

Easiest way to write a Python program with access to Django database functionality

百般思念 提交于 2019-12-04 15:17:43
问题 I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information. What is the easiest way to make a Python program have access to my particular Django application and the Django ORM? 回答1: from django.core

Many to many relation. ORM Django

一曲冷凌霜 提交于 2019-12-04 15:16:47
问题 class Toy(models.Model): name = models.CharField(max_length=20) desc = models.TextField() class Box(models.Model): name = models.CharField(max_length=20) proprietor = models.ForeignKey(User, related_name='User_Box') toys = models.ManyToManyField(Toy, blank=True) How to create a view that add Toy to Box? def add_this_toy_to_box(request, toy_id): 回答1: You can use Django's RelatedManager: A “related manager” is a manager used in a one-to-many or many-to-many related context. This happens in two

Django ORM. Joining subquery

怎甘沉沦 提交于 2019-12-04 15:05:29
I have a table which contains list of some web sites and a table with statistics of them. class Site(models.Model): domain_name = models.CharField( max_length=256, unique=True, ) class Stats(models.Model): date = models.DateField() site = models.ForeignKey('Site') google_pr = models.PositiveIntegerField() class Meta: unique_together = ('site', 'date') I want to see all sites and statistics for a concrete date. If a stats record for the date doesn't exist, then the selection must contain only site. If I use: Site.objects.filter(stats__date=my_date) I will not get sites which have no records for

Timedelta between two fields

蓝咒 提交于 2019-12-04 09:26:33
I'm looking for objects where the timedelta between two fields is greater than a certain number of days. Baiscally I have a date when a letter is sent, and a date when an approval is received. When no approval is received in let's say 30 days, then these objects should be included in the queryset. I can do something like the below, where the delta is something static. However I don't need datetime.date.today() as a start but need to compare against the other object. delta = datetime.date.today() - datetime.timedelta(30) return qs.filter(letter_sent__isnull=False)\ .filter(approval_from__isnull

Django Aggregation - Expression contains mixed types. You must set output_field

末鹿安然 提交于 2019-12-04 09:11:00
问题 I'm trying to achive an Aggregation Query and that's my code: TicketGroup.objects.filter(event=event).aggregate( total_group=Sum(F('total_sold')*F('final_price'))) I have 'total_sold' and 'final_price' in TicketGroup object and all what I want to do is sum and multiply values to get the total sold of all TicketGroups together. All I get is this error: Expression contains mixed types. You must set output_field What I am doing wrong, since I'm calling 'total_group' as my output field? Thanks!

Is django prefetch_related supposed to work with GenericRelation

末鹿安然 提交于 2019-12-04 08:49:59
问题 UPDATE: An Open Ticked about this issue: 24272 What's all about? Django has a GenericRelation class, which adds a “reverse” generic relationship to enable an additional API . It turns out we can use this reverse-generic-relation for filtering or ordering , but we can't use it inside prefetch_related . I was wondering if this is a bug, or its not supposed to work, or its something that can be implemented in the feature. Let me show you with some examples what I mean. Lets say we have two main