django-database

Simple Subquery with OuterRef

牧云@^-^@ 提交于 2019-11-29 21:33:42
I am trying to make a very simple Subquery that uses OuterRef (not for practical purposes, just to get it working), but keep running into same error. posts/models.py from django.db import models class Tag(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=120) tags = models.ManyToManyField(Tag) def __str__(self): return self.title manage.py shell code >>> from django.db.models import OuterRef, Subquery >>> from posts.models import Tag, Post >>> tag1 = Tag.objects.create(name='tag1') >>> post1

Django __in lowercase

烈酒焚心 提交于 2019-11-29 12:25:18
I'm using django-taggit , which handles the attachment of tags to arbitrary content types. I imported a large tag list, which contains many uppercase words, as well as lowercase words. Now, I' trying to get objects of another class containing a set of tags, but I want to compare case insensitively. When I do this: Media.objects.filter(tags__name__in=['tag1', 'tag2']) objects containing e.g. the tag "Tag1" are not found, only those ones with "tag1" or "tag2". Is there any possibility in the django orm to do something like: Media.objects.filter(tags__name__iin=['tag1', 'tag2']) that acts like

Django update table using data from another table

最后都变了- 提交于 2019-11-29 06:06:10
问题 I have 2 tables products and catagories connected by foreign key. I need to update field products.new_cost using field catagories.price_markup as following: UPDATE products p INNER JOIN categories c ON p.category_id = c.id SET p.new_cost = ROUND(p.pleer_cost * (1 + c.price_markup/100), -1) WHERE p.update = 1 In SQL it's so easy, but how to do it using Django ORM? My simplified try doesn't work Cannot resolve keyword 'category.price_markup' into field. : Product.actived.select_related(

How can I subtract or add 100 years to a datetime field in the database in Django?

前提是你 提交于 2019-11-29 04:43:41
问题 How can I subtract or add 100 years to a datetime field in the database in Django? The date is in database, I just want to directly update the field without retrieving it out to calculate and then insert. 回答1: I would use the relativedelta function of the dateutil.relativedelta package, which will give you are more accurate 'n-years ago' calculation: from dateutil.relativedelta import relativedelta import datetime years_ago = datetime.datetime.now() - relativedelta(years=5) Then simply update

Prevent Django from querying for ForeignKey options for every form in ModelFormSet

微笑、不失礼 提交于 2019-11-28 20:54:06
I'm building a csv import form for my Django application and want to display the to-be-imported rows in a ModelFormSet for validational purposes. Therefore I added a view to the relevant ModelAdmin which reads the lines from the csv and prints a ModelFormSet(queryset=an_empty_queryset, initial={data_from_the_csv}) . The problem is that the model references three other models via ForeignKey fields and for each field in each form in the formset a database query is issued in order to populate the ModelChoiceField 's options. Why doesn't Django cache the form (as it is used several times) or is

dynamically set database based on request in django

☆樱花仙子☆ 提交于 2019-11-28 05:09:10
I am writing a multi-tenant application with python-django. I want to set database connection based on each request.I thought i could write a middleware where we set the database to be used for that particular database. import re from django.db import connections class SetTenantDatabase(object): def process_request(self, request): pattern = re.compile("\\b(http://|https://|www.|.com|8000|:|//)\\W\\d+", re.I) words = request.get_host() db_name = [pattern.sub("", words)][0].split('.')[0] connections.databases['new-alias'] = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME

Django ManyToMany through with multiple databases

耗尽温柔 提交于 2019-11-28 02:52:11
问题 TLTR: Django does not include database names in SQL queries , can I somehow force it to do this or is there a workaround? The long version: I have two legacy MySQL databases (Note: I have no influence on the DB layout) for which I'm creating a readonly API using DRF on Django 1.11 and python 3.6 I'm working around the referential integrity limitation of MyISAM DBs by using the SpanningForeignKey field suggested here: https://stackoverflow.com/a/32078727/7933618 I'm trying to connect a table

Django - how to specify a database for a model?

只愿长相守 提交于 2019-11-27 21:10:42
Is there a way to specify that a model (or app, even) should only ever use one particular database? I am working with a legacy database that I don't want to change. I have two databases - the 'default' is an sqlite one that could be used for admin etc, and the legacy one. I used inspectdb to create a model for (part of) the legacy database, and it has managed = False . But is there a way to specify in the model itself that it only applies to a particular database? I see that you can specify using=databasename in some query sets etc but this is no good for things like Databrowse (and possibly

Django - Rollback save with transaction atomic

十年热恋 提交于 2019-11-27 20:06:25
I am trying to create a view where I save an object but I'd like to undo that save if some exception is raised. This is what I tried: class MyView(View): @transation.atomic def post(self, request, *args, **kwargs): try: some_object = SomeModel(...) some_object.save() if something: raise exception.NotAcceptable() # When the workflow comes into this condition, I think the previous save should be undome # Whant am I missing? except exception.NotAcceptable, e: # do something What am I doing wrong? even when the exception is raised some_object is still in DataBase. Atomicity Documentation To

Prevent Django from querying for ForeignKey options for every form in ModelFormSet

亡梦爱人 提交于 2019-11-27 13:17:43
问题 I'm building a csv import form for my Django application and want to display the to-be-imported rows in a ModelFormSet for validational purposes. Therefore I added a view to the relevant ModelAdmin which reads the lines from the csv and prints a ModelFormSet(queryset=an_empty_queryset, initial={data_from_the_csv}) . The problem is that the model references three other models via ForeignKey fields and for each field in each form in the formset a database query is issued in order to populate