All Questions

Tagged with
Filter by
Sorted by
Tagged with
111 votes
8 answers
239k views

How to update() a single model instance retrieved by get() on Django ORM?

I have a function which currently calls Models.object.get(), which returns either 0 or 1 model objects: if it returns 0, I create a new model instance in the except DoesNotExist clause of the ...
zhuyxn's user avatar
  • 6,901
110 votes
4 answers
81k views

Create if doesn't exist

I have a Django application that reads data from a web API and puts it in a database. Is there a way to create a new object from a mode but prevent the duplicate exception if the object already exists?...
user1094786's user avatar
  • 6,690
97 votes
6 answers
187k views

Check if an object exists

I need to check if Model.objects.filter(...) turned up anything, but do not need to insert anything. My code so far is: user_pass = log_in(request.POST) # form class if user_pass.is_valid(): ...
sinθ's user avatar
  • 11.3k
97 votes
1 answer
56k views

Django's ManyToMany Relationship with Additional Fields

I want to store some additional information in that, automatically created, ManyToMany join-table. How would I do that in Django? In my case I have two tables: "Employees" and "Projects". What I ...
rrb_bbr's user avatar
  • 3,026
96 votes
7 answers
103k views

Raise a validation error in a model's save method in Django

I'm not sure how to properly raise a validation error in a model's save method and send back a clear message to the user. Basically I want to know how each part of the "if" should end, the one where ...
Bastian's user avatar
  • 5,715
95 votes
3 answers
19k views

models.py getting huge, what is the best way to break it up?

Directions from my supervisor: "I want to avoid putting any logic in the models.py. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes ...
Eddified's user avatar
  • 3,144
92 votes
5 answers
86k views

Django Queryset with filtering on reverse foreign key

I have the following Django model: class Make: name = models.CharField(max_length=200) class MakeContent: make = models.ForeignKey(Make) published = models.BooleanField() I'd like to know ...
Julian A.'s user avatar
  • 11.2k
86 votes
8 answers
54k views

Django get list of models in application

So, i have a file models.py in MyApp folder: from django.db import models class Model_One(models.Model): ... class Model_Two(models.Model): ... ... It can be about 10-15 classes. How to find ...
Feanor's user avatar
  • 3,618
81 votes
2 answers
56k views

Django - Model graphic representation (ERD) [closed]

I'm searching a way to represent my Django project model graphically. Is there a "native" way to do this kind of ERD (diagram) ? Update following @Etienne instructions Here is an example of ...
Pierre de LESPINAY's user avatar
79 votes
6 answers
88k views

Django required field in model form

I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py class CircuitForm(ModelForm): class Meta: model = Circuit ...
Ryan's user avatar
  • 1,095
75 votes
4 answers
85k views

How can I set two primary key fields for my models in Django?

I have a model like this: class Hop(models.Model): migration = models.ForeignKey('Migration') host = models.ForeignKey(User, related_name='host_set') How can I have the primary key be the ...
Vahid Kharazi's user avatar
73 votes
11 answers
34k views

Case insensitive unique model fields in Django?

I have basically a username is unique (case insensitive), but the case matters when displaying as provided by the user. I have the following requirements: field is CharField compatible field is ...
noobzie's user avatar
  • 1,109
68 votes
5 answers
88k views

Populating django field with pre_save()?

class TodoList(models.Model): title = models.CharField(maxlength=100) slug = models.SlugField(maxlength=100) def save(self): self.slug = title super(TodoList, self).save() ...
Derek's user avatar
  • 12.2k
65 votes
3 answers
44k views

How can I iterate over ManyToManyField?

A simple question and yet I can't find an answer for it. I have a model with a ManyToMany field: class Stuff(models.Model): things = models.ManyToManyField(Thing) then in a different function I ...
Goro's user avatar
  • 10.1k
60 votes
9 answers
35k views

Can Django automatically create a related one-to-one model?

I have two models in different apps: ModelA and ModelB. They have a one-to-one relationship. Is there a way django can automatically create and save ModelB when ModelA is saved? class ModelA(models....
vagabond's user avatar
  • 601
58 votes
1 answer
57k views

Django model: NULLable field

I'm working on a django project where I need a DateField to sometimes be empty. My model looks like this: #models.py end = models.DateField(default=None, blank=True) But when I run python manage.py ...
Robin's user avatar
  • 9,555
57 votes
5 answers
14k views

Should I avoid multi-table (concrete) inheritance in Django by any means?

Many experienced developers recommend against using Django multi-table inheritance because of its poor performance: Django gotcha: concrete inheritance by Jacob Kaplan-Moss, a core contributor of ...
utapyngo's user avatar
  • 7,006
54 votes
5 answers
18k views

How do I get the default value for a field in a Django model?

I have a Django model with some fields that have default values specified. I am looking to grab the default value for one of these fields for us later on in my code. Is there an easy way to grab a ...
mikec's user avatar
  • 3,623
50 votes
2 answers
55k views

optional fields in django models

I have the following model in django. class Link(models.Model): name = models.CharField(max_length=100) url = models.CharField(max_length=100) tag = models.CharField(max_length=100) ...
eatonphil's user avatar
  • 13.4k
48 votes
2 answers
43k views

How can I fill up form with model object data?

I want to fill up form with data from model instance. But my form has less fields than model. If I have code like this: class Item(models.Model) name = models.CharField(max_length=100) price =...
krzyhub's user avatar
  • 6,375
47 votes
3 answers
78k views

ValueError - Cannot assign: must be an instance

I get the following error when I try to run an insert into one of my tables. Cannot assign "1": "Team.department_id" must be a "Department" instance Admittedly I'm ...
rahimbah's user avatar
  • 629
46 votes
4 answers
47k views

Do properties work on Django model fields?

I think the best way to ask this question is with some code... can I do this: class MyModel(models.Model): foo = models.CharField(max_length = 20) bar = models.CharField(max_length = ...
Jiaaro's user avatar
  • 75.7k
44 votes
3 answers
50k views

Django Pass Multiple Models to one Template

I am building an address book that includes the relationships between entries, etc. I have separate models for Individuals, Companies, Venues, and Roles. On my index page I would like to list all of ...
Nahanaeli Schelling's user avatar
43 votes
3 answers
72k views

Restrict django FloatField to 2 decimal places

I am looking for a way to limit the FloatField in Django to 2 decimal places. Has anyone got a clue of how this could be done without having to use a DecimalField? I tried decimal_places=2, but this ...
Aidan Doherty's user avatar
43 votes
6 answers
75k views

How can I change a Django form field value before saving?

if request.method == 'POST': userf = UsersModelForm(request.POST) username = userf.data['username'] password = userf.data['password'] passwordrepeat = userf.data['passwordrepeat'] ...
cola's user avatar
  • 12.3k
43 votes
1 answer
40k views

AttributeError: 'ManyRelatedManager' object has no attribute 'add'? I do like in django website but got this error

for item in data: category_id = item['category_id'] del item['category_id'] category = Category.objects.get(pk=category_id) code = item['code'] try: article = Article....
Totty.js's user avatar
  • 15.7k
40 votes
3 answers
27k views

How to get the app a Django model is from?

I have a model with a generic relation: TrackedItem --- genericrelation ---> any model I would like to be able to generically get, from the initial model, the tracked item. I should be able to ...
Bite code's user avatar
  • 588k
39 votes
5 answers
30k views

Check if a OneToOne relation exists in Django

Now I'm using django 1.6 I have two models relates with a OneToOneField. class A(models.Model): pass class B(models.Model): ref_a = models.OneToOneField(related_name='ref_b', null=True) ...
Alfred Huang's user avatar
36 votes
9 answers
25k views

Django self-recursive foreignkey filter query for all childs

I have this model with a self referencing Foreign Key relation: class Person(TimeStampedModel): name = models.CharField(max_length=32) parent = models.ForeignKey('self', null=True, blank=True,...
Ahsan's user avatar
  • 11.8k
36 votes
2 answers
17k views

How to have two models reference each other Django

I have the following code: class Game(models.Model): title = models.CharField(max_length=50) summery = models.CharField(max_length=500) key = models.IntegerField() pin = models....
sinθ's user avatar
  • 11.3k
34 votes
5 answers
50k views

How can my django model DateField add 30 days to the provided value?

as the title suggests. I want to add 30 days to the DateField field. This is auto populated on creation of record using auto_now_add=True Any ideas how to go about doing this? Thanks
dotty's user avatar
  • 41k
34 votes
7 answers
36k views

Django model instances primary keys do not reset to 1 after all instances are deleted

I have been working on an offline version of my Django web app and have frequently deleted model instances for a certain ModelX. I have done this from the admin page and have experienced no issues. ...
pj2452's user avatar
  • 905
32 votes
4 answers
44k views

How to set initial data for Django admin model add instance form?

How can I set an initial value of a field in the automatically generated form for adding a Django model instance, before the form is displayed? I am using Django 1.3.1. My model is the following: ...
Martijn de Milliano's user avatar
31 votes
3 answers
36k views

Better option to check if a particular instance exists django

Which of the two is a better and efficient option to check if an instance exists. There can only be one record returned at most. 1) Use the filter option and see if it exists: x = MyObject.objects....
Aswin Murugesh's user avatar
31 votes
2 answers
20k views

Access fields in Django intermediate model

I'm creating a Person Group and Membership as described in Django docs for intermediate model. class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): ...
pablo's user avatar
  • 2,789
30 votes
4 answers
31k views

Override django's model delete method for bulk deletion

I'm overriding Django's model delete method in order to delete orphan files in the disk for image fields, something like this: class Image(models.Model): img = models.ImageField(upload_to=...
Kilian Perdomo Curbelo's user avatar
28 votes
3 answers
25k views

django update_or_create gets "duplicate key value violates unique constraint "

Maybe I misunderstand the purpose of Django's update_or_create Model method. Here is my Model: from django.db import models import datetime from vc.models import Cluster class Vmt(models.Model): ...
Red Cricket's user avatar
  • 10.2k
28 votes
3 answers
14k views

Django model inheritance: Create a subclass using existing super class

I'm using multi-table-inheritance, and want to know how to create an inherited type from an instance of the superclass. Using the example given in the documentation: class Place(models.Model): ...
michel.iamit's user avatar
  • 5,886
28 votes
3 answers
8k views

Python/Django: synonym for field "type" in database model (reserved built-in symbol)

I created a django project. It contains a model class with a "type" attribute. I think that "type" is the most appropriate term to describe that field, because it defines the kind of the entry. ...
Alp's user avatar
  • 29.5k
27 votes
4 answers
25k views

How to remove the prefix of a table for a Django model?

I create a new Django app (not project) called Bussinesses, then add following class to the models.py. class Bussinesses(models.Model): business_email = models.EmailField() password = models....
redice's user avatar
  • 8,567
26 votes
1 answer
10k views

Django MVC pattern for non database driven models?

I'm just working my way through Django, and really liking it so far, but I have an issue and I'm not sure what the typical way to solve it. Suppose I have a View which is supposed to be updated when ...
DevDevDev's user avatar
  • 5,147
26 votes
1 answer
9k views

Django: Creating a Mixin for Reusable Model Fields

I've got a few fields that I want to add to most every model in my project. For example, these fields are "tracking fields" such as a created date, an update date, and an "active" flag. I'm ...
Joe J's user avatar
  • 10.5k
25 votes
3 answers
64k views

Django models filter by foreignkey

I'm having some trouble in filtering objects from a set of models. Here is the problem: I have 3 classes: class Autor(models.Model): nome = models.CharField(max_length=50) slug = models....
maloky's user avatar
  • 353
25 votes
9 answers
50k views

How to store a dictionary in a Django database model's field

I need to save a dictionary in a model's field. How do I do that? For example I have this code: def create_random_bill(self): name_chars = re.compile("[a-zA-Z0-9 -_]") bill_name = "".join(...
Radu Gheorghiu's user avatar
24 votes
1 answer
27k views

Django CharField with no max length

I have a frontend that will be sending bas64 images, I will put those very large strings on a variable and send it to a form. What kind of FormField can I use? The regular CharFields need a ...
Alejandro Veintimilla's user avatar
23 votes
12 answers
40k views

Error in admin: __str__ returned non-string (type NoneType)

The admin returns this error when trying to add an instance to one of my models. The model itself has a correct str() method and contains no instances yet. Also tried replacing the str() method with a ...
Roy Prins's user avatar
  • 2,940
23 votes
5 answers
23k views

Django ORM how to Round an Avg result

I have a model in which I use Django ORM to extract Avg of values from the table. I want to Round that Avg value, how do I do this? See below I am extracting Avg price from Prices model grouped by ...
Ami's user avatar
  • 515
23 votes
2 answers
8k views

Django: Using F arguments in datetime.timedelta inside a query

Using Django model syntax, if I do this: ThatModel.objects.filter( last_datetime__lte=now + datetime.timedelta(seconds=F("interval"))) I get: TypeError: unsupported type for timedelta days ...
Synthead's user avatar
  • 2,272
23 votes
1 answer
12k views

How do Django Fixtures handle ManyToManyFields?

I'm trying to load in around 30k xml files from clinicaltrials.gov into a mySQL database, and the way I am handling multiple locations, keywords, etc. are in a separate model using ManyToManyFields. ...
CMaury's user avatar
  • 1,283
23 votes
2 answers
13k views

Can you add parameters to Django custom admin actions?

For example (not the case, but just to illustrate) if I wanted to add an action to set a specific field in the selected items to X. Is it possible to add an action to allow X to be entered as opposed ...
nickponline's user avatar
  • 25.6k

1
2 3 4 5
71