django-models

Django - Custom virtual model field with companion stored field

I would like to have a ConfirmationField field type. I want this field to work like a boolean field. I don't need to store this information on database instead I would like to store the date of confirmation on a seperate field. class MyModel(models.Model): confirmation = ConfirmationField() m = MyModel() m.confirmation # False m.c...

Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object

I've models for Books, Chapters and Pages. They are all written by a User: from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey...

I've got an existing Django app with a lack of database indexes. Is there a way to automatically generate a list of columns that need indexing?

The beauty of ORM lulled me into a soporific sleep. I was thinking maybe some middleware that logs which columns are involved in WHERE clauses? but is there anything built into MySQL that might help? ...

What is the best approach to implement configuration app with Django?

I need to program kind of configuration registry for Django-based application. Requirements: Most likely param_name : param_value structure Editable via admin interface Has to work with syncdb. How to deal with a situation in which other apps depend on configuration model and the model itself has not been initialized yet in DB? Let's...

Bisect queryset around another model's queryset

I'm writing an user-driven app with several zones to it. I want to allow users to customise their messaging settings so they only get emails on the parts and actions they care about. I've drawn up the following Class: class EmailSetting(models.Model): user = models.ForeignKey(User, related_name="%(class)s_related_user") key = mo...

Is it "better" to have an update field or COUNT query?

In a Django App I'm working on I've got this going on: class Parent(models.Model): name = models.CharField(...) def num_children(self): return Children.objects.filter(parent=self).count() def avg_child_rating(self): return Child.objects.filter(parent=self).aggregate(Avg('rating')) class Child(models.Model)...

Unique fields that allow nulls in Django

I have model Foo which has field bar. The bar field should be unque, but allow nulls in it, meaning I want to allow more than one record if bar field is null, but if it is not null the values must be unque. Here is my model: class Foo(models.Model): name = models.CharField(max_length=40) bar = models.CharField(max_length=40, un...

Django ORM: Get most recent prior object that meets a certain condition

Hi there, Given an object like: class M(models.Model): test = models.BooleanField() created_date = models.DateTimeField(auto_now_add=True) Given sample data (assume monotonically increasing automatic created_date): M(test=False).save() M(test=True).save() M(test=False).save() X = M(test=True).save() M(test=False).save() Y =...

How to make a model instance read-only after saving it once?

One of the functionalities in a Django project I am writing is sending a newsletter. I have a model, Newsletter and a function, send_newsletter, which I have registered to listen to Newsletter's post_save signal. When the newsletter object is saved via the admin interface, send_newsletter checks if created is True, and if yes it actually...

How to prevent overwriting an object someone else has modified

I would like to find a generic way of preventing to save an object if it is saved after I checked it out. We can assume the object has a timestamp field that contains last modification time. If I had checked out (visited a view using a ModelForm for instance) at t1 and the object is saved again at t2, given t2 > t1 I shouldn't be able t...

How to specify uniqueness for a tuple of field in a Django model

Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field? Or do I need to check this constraint in the clean() method? ...

group by in django

How can i create simple group by query in trunk version of django? I need something like SELECT name FROM mytable GROUP BY name actually what i want to do is simply get all entries with distinct names. ...

Get foreign key without requesting the whole object

Hi, I have a model Foo which have a ForeignKey to the User model. Later, I need to grab all the User's id and put then on a list foos = Foo.objects.filter(...) l = [ f.user.id for f in foos ] But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist in each Foo...

Reversing a ManyToMany relationship

I have Boys and Toys. Two django models. Toys can be owned by more than one Boy and each boy can own more than one Toy... So I've put a ManyToMany field in Boy. If I want a list of toys owned by a single boy, it's easy. So good so far. But now I need to get a list of Boys based on a Toy instance. The relationship should be symmetrical...

Django: ModelMultipleChoiceField doesn't select initial choices

ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example: http://code.djangoproject.com/ticket/5247#comment:6 My models and form: class Company(models.Model): company_name = models.CharField(max_length=200) class Contact(models.Model): company = models.ForeignK...

ForeignKey doesn't create a valid form field

I have an Entry. There's a field, brotherEntry, that could point to another Entry. So when I show the form writeEntry, the user can select a brother entry from the list of entries already inserted. However, that list doesn't show all of them, just a few. I can't figure out why is doing that... Any idea? #models.py class Entry(models.Mod...

Django workflow when modifying models frequently?

Hi gents, as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. Modify the model. De...

django model question ( newbie )

First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject.com ) : class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): # Note use of django...

Django: How to create a model dynamically just for testing

I have a Django app that requires a settings attribute in the form of: RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) Then hooks their post_save signal to update some other fixed model depending on the attributeN defined....

Django - how do you turn an InMemoryUploadedFile into an ImageField ?

I've been trying help(django.db.models.ImageField) and dir(django.db.models.ImageField), looking for how you might create a ImageField object from an image that is uploaded. request.FILES has the images as InMemoryUploadedFile, but I'm trying to save a model that contains an ImageField, so how do I turn the InMemoryUploadedFile into the...