django-orm

Many to many relation. ORM Django

我与影子孤独终老i 提交于 2019-12-03 09:39:11
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): K Z 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 cases: The “other side” of a ForeignKey relation. That is: class Reporter(models.Model): ... class

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

≯℡__Kan透↙ 提交于 2019-12-03 08:52:08
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? from django.core.management import setup_environ from django.core.mail import EmailMultiAlternatives, send_mail from django.contrib

When does Django look up the primary key of foreign keys?

旧时模样 提交于 2019-12-03 08:30:01
问题 I have two simple models, one representing a movie an the other representing a rating for a movie. class Movie(models.Model): id = models.AutoField(primary_key=True) title = models.TextField() class Rating(models.Model): id = models.AutoField(primary_key=True) movie = models.ForeignKey(Movie) rating = models.FloatField() My expectation is that I would be able to first create a Movie and a Review referencing that movie then commit them both to the database, as long as I committed the Movie

Django: get aggregated value of two multiplied columns

假装没事ソ 提交于 2019-12-03 08:11:37
I need to get aggregated value of two columns. So first multiple them together and then get theirs sum() . Code below naturally does not work, it is just for clarification. Is it somehow possible or should I use raw SQL? SomeModel.objects .filter(**something) .aggregate(Sum('one_column' * 'another_col')) You don't need that much raw SQL using extra() . obj = SomeModel.objects.filter(**something).extra( select = {'total': 'SUM(one_column * another_column)'}, ) Antstud As I answered here https://stackoverflow.com/a/36024089/4614802 the correct solution depends on django version. For django < 1.8

Django: Force select related?

不羁的心 提交于 2019-12-03 06:32:32
问题 I've created a model, and I'm rendering the default/unmodified model form for it. This alone generates 64 SQL queries because it has quite a few foreign keys, and those in turn have more foreign keys. Is it possible to force it to always (by default) perform a select_related every time one of these models are returned? 回答1: You can create a custom manager, and simply override get_queryset for it to apply everywhere. For example: class MyManager(models.Manager): def get_queryset(self): return

Django 1.8 - Intermediary Many-to-Many-Through Relationship - What is the consequence of where 'ManytoManyField' is used?

*爱你&永不变心* 提交于 2019-12-03 06:13:20
An example Many-to-Many through relationship in Django: class First(models.Model): seconds = models.ManyToManyField(Second, through='Middle') class Middle(models.Model): first = models.ForeignKey(First) second = models.ForeignKey(Second) class Second(models.Model): Following the documentation on intermediary models , only one model of the pair to be related contains the ManytoManyField , model First in the example above. Is this correct? If so, which model should contain the ManytoManyField field? Are there any differences in using the relationship from either end depending on where the

Annotating a Sum results in None rather than zero

元气小坏坏 提交于 2019-12-03 05:28:41
问题 I'm making a QA site that is similar to the page you're on right now. I'm attempting to order answers by their score, but answers which have no votes are having their score set to None rather than 0. This results in answers with no votes being at the bottom of the page below negatively ranked answers. How can I make the annotated score be zero when there are no votes for an answer? Here's my model: from django.contrib.auth.models import User Answer(models.Model): //some fields here pass VOTE

Aggregation of an annotation in GROUP BY in Django

Deadly 提交于 2019-12-03 04:40:53
问题 UPDATE Thanks to the posted answer, I found a much simpler way to formulate the problem. The original question can be seen in the revision history. The problem I am trying to translate an SQL query into Django, but am getting an error that I don't understand. Here is the Django model I have: class Title(models.Model): title_id = models.CharField(primary_key=True, max_length=12) title = models.CharField(max_length=80) publisher = models.CharField(max_length=100) price = models.DecimalField

django forms: editing multiple sets of related objects in a single form

僤鯓⒐⒋嵵緔 提交于 2019-12-03 03:34:55
I'm trying to do something that should be very common: add/edit a bunch of related models in a single form. For example: Visitor Details: Select destinations and activities: Miami [] - swimming [], clubbing [], sunbathing[] Cancun [] - swimming [], clubbing [], sunbathing[] My models are Visitor, Destination and Activity, with Visitor having a ManyToMany field into Destination through an intermediary model, VisitorDestination, which has the details of the activities to be done on the destination (in itself a ManyToMany field into Activity). Visitor ---->(M2M though VisitorDestination) --------

Django ORM: caching and manipulating ForeignKey objects

你。 提交于 2019-12-03 03:22:00
Consider the following skeleton of a models.py for a space conquest game: class Fleet(models.Model): game = models.ForeignKey(Game, related_name='planet_set') owner = models.ForeignKey(User, related_name='planet_set', null=True, blank=True) home = models.ForeignKey(Planet, related_name='departing_fleet_set') dest = models.ForeignKey(Planet, related_name='arriving_fleet_set') ships = models.IntegerField() class Planet(models.Model): game = models.ForeignKey(Game, related_name='planet_set') owner = models.ForeignKey(User, related_name='planet_set', null=True, blank=True) name = models.CharField