All Questions

Tagged with
Filter by
Sorted by
Tagged with
134 votes
6 answers
170k views

How to query database by id using SqlAlchemy?

I need to query a SQLAlchemy database by its id something similar to User.query.filter_by(username='peter') but for id. How do I do this? [Searching over Google and SO didn't help]
user avatar
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
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
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
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
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
65 votes
1 answer
14k views

Is it bad practice to include non-validating methods in a pydantic model?

I'm using pydantic 1.3 to validate models for an API I am writing. Is it common/good practice to include arbitrary methods in a class that inherits from pydantic.BaseModel? I need some helper methods ...
ccred's user avatar
  • 653
51 votes
3 answers
58k views

Local functions in Python [duplicate]

In the following Python code, I get an UnboundLocalError. As I understand it, local functions share the local variables of the containing function, but this hardly seems to be the case here. I ...
Matt Joiner's user avatar
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
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
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
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
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
12 answers
89k views

Cast string to float is not supported in Linear Model

I keep getting this error in my linear model: Cast string to float is not supported Specifically, the error is on this line: results = m.evaluate(input_fn=lambda: input_fn(df_test), steps=1) If ...
user3764124's user avatar
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
25 votes
12 answers
29k views

Spacy link error

When running: import spacy nlp = spacy.load('en') the following is printed: Warning: no model found for 'en' Only loading the 'en' tokenizer. /site-packages/spacy/data is empty with the ...
negfrequency's user avatar
  • 1,879
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
25 votes
1 answer
3k views

Trigger Odoo fields_view_get dynamically after all records being loaded and fields_view_get function called

I’d like to trigger the fields_view_get function dynamically after doing some functions. I override the function fields_view_get and return my results. This gets affected on XML view only at first ...
Hilar AK's user avatar
  • 1,675
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
21 votes
1 answer
6k views

Django models: mutual references between two classes and impossibility to use forward declaration in python

I have defined two models where each one references the other, like so: class User(models.Model): # ... loves = models.ManyToManyField(Article, related_name='loved_by') class Article(models....
koo's user avatar
  • 2,908
21 votes
4 answers
18k views

How to assign items inside a Model object with Django?

Is it possible to override values inside a Model? I am getting 'MyModel' object does not support item assignment. my_model = MyModel.objects.get(id=1) print my_model.title if my_model.is_changed: ...
Pompeyo's user avatar
  • 1,469
21 votes
3 answers
22k views

SQLAlchemy - order_by on relationship for join table

I'm using declarative SQLAlchemy and I have three models: Role, Permission, and RolePermission. In my Role model, I have the following: class Role(Base): name = Column(u'NAME', VARCHAR(50), ...
Sarah Vessels's user avatar
21 votes
4 answers
9k views

ForeignKey to abstract class (generic relations)

I'm building a personal project with Django, to train myself (because I love Django, but I miss skills). I have the basic requirements, I know Python, I carefully read the Django book twice if not ...
pistache's user avatar
  • 6,003
20 votes
2 answers
12k views

Default filter in Django model

Is is possible to set a default filter in Django models? Something like: class MyModel(models.Model): timestamp = models.DateTimeField(default=datetime.utcnow) active = models.BooleanField(...
SimonSays's user avatar
  • 10.9k
20 votes
2 answers
17k views

Django: Grab a set of objects from ID list (and sort by timestamp)

I have a list of IDs for objects that I need to grab, then I have to sort them by their timestamp. Here's how I was going to do it: For i in object_ids: instance = Model.objects.get(id = i) # ...
Goro's user avatar
  • 10.1k
20 votes
3 answers
51k views

Import data from excel spreadsheet to django model

I'm building a website that'll have a django backend. I want to be able to serve the medical billing data from a database that django will have access to. However, all of the data we receive is in ...
TechEmperor95's user avatar
19 votes
2 answers
22k views

Python/Django: Adding custom model methods?

Using for example class model(models.Model) .... def my_custom_method(self, *args, **kwargs): #do something When I try to call this method during pre_save, save, post_save etc, ...
Izz ad-Din Ruhulessin's user avatar
19 votes
1 answer
23k views

How to use full_clean() for data validation before saving in Django 1.5 gracefully?

I think Django's model validation is a little inconvenient for those models that don't use built-in ModelForm, though not knowing why. Firstly, full_clean() needs called manually. Note that ...
ray6080's user avatar
  • 893
18 votes
5 answers
44k views

How to load a pre-trained Word2vec MODEL File and reuse it?

I want to use a pre-trained word2vec model, but I don't know how to load it in python. This file is a MODEL file (703 MB). It can be downloaded here: http://devmount.github.io/GermanWordEmbeddings/
Vahid SJ's user avatar
  • 413
18 votes
3 answers
36k views

Can I create model in Django without automatic ID?

I need a table without a primary key (in Django it was created automatically). So my question is: Can I create a model without an ID/primary key? I'm using Django 1.7.
HQM's user avatar
  • 566
18 votes
6 answers
52k views

pydantic exclude multiple fields from model

In pydantic is there a cleaner way to exclude multiple fields from the model, something like: class User(UserBase): class Config: exclude = ['user_id', 'some_other_field'] I am ...
muon's user avatar
  • 13.5k
18 votes
2 answers
35k views

How to set value of a ManyToMany field in Django?

while learning Django to do web programming,I faced this problem. I searched Google and Django's official website biut could not find any answer. Please help me. System environment: Fedora 18 Python ...
kidney win's user avatar
18 votes
3 answers
9k views

Is there a way to transparently perform validation on SQLAlchemy objects?

Is there a way to perform validation on an object after (or as) the properties are set but before the session is committed? For instance, I have a domain model Device that has a mac property. I would ...
Beau Simensen's user avatar
17 votes
6 answers
21k views

How to choose the value and label from Django ModelChoiceField queryset

I was trying to create a django form and one of my field contain a ModelChoiceField class FooForm(forms.Form): person = forms.ModelChoiceField(queryset=Person.objects.filter(is_active=True)....
helloworld2013's user avatar
17 votes
3 answers
15k views

How to run multiple graphs in a Session - Tensorflow API

Tensorflow API has provided few pre-trained models and allowed us to trained them with any dataset. I would like to know how to initialize and use multiple graphs in one tensorflow session. I want ...
saikishor's user avatar
  • 918
16 votes
4 answers
50k views

Django Models Number Field

In Django I'm trying to create a model which will contain a field for player's shirt numbers and was wondering if there is a way to restrict the field to be only numerical inputs. Currently I have in ...
Edward Knight's user avatar
16 votes
3 answers
12k views

how to get dict of model objects keyed by field

Assuming I have Django model called 'Blog' with a primary key field 'id', is there a query I can run that will return a dictionary with keys of the id values indexing the Blog model instances? ...
Alb's user avatar
  • 3,651
16 votes
2 answers
23k views

Inserting NULL as default in SQLAlchemy?

I have the following column in SQLAlchemy: name = Column(String(32), nullable=False) I want that if no value is passed onto an insertion, it should enter a default value of either completely blank ...
sshussain270's user avatar
  • 1,845
16 votes
4 answers
3k views

Decoupling Domain classes from Django Model Classes

So I have completed my OO analysis and design of a web application that I am building and am now getting into implementation. Design decisions have been made to implement the system using Python and ...
Michael's user avatar
  • 249
16 votes
6 answers
14k views

Model limit_choices_to={'user': user}

I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is ...
AbeEstrada's user avatar
  • 1,090
15 votes
1 answer
23k views

How to select QTableView row with one click

When one of the QTableView's QModelIndex is clicked I want to select an entire row of the same-row-indexes. To accomplish this I connect QTableView's clicked signal to a custom viewClicked() method ...
alphanumeric's user avatar
  • 18.7k
15 votes
3 answers
15k views

Conditionally Require Only One Field In Django Model Form

Anyway to make a field conditionally required based on whether or not another field in the same form has been filled out? If field1 has no data, but field2 does form is valid. If field1 has no ...
Derek Reynolds's user avatar
15 votes
5 answers
15k views

Django DateTimeField auto_now_add not working

In one of the model i have set one timestamp field as follows: created_datetime = models.DateTimeField(auto_now_add = True) While in shell i am able to create a obj and save it, however in my ...
Arun's user avatar
  • 856
15 votes
1 answer
7k views

How to move model to the other section in Django's site admin

Is it possible to move default Groups model from 'Authentication and Authoriation' section (on the Django admin site) to custom one and how to achieve that? Let's start from the beginning in the ...
Tomasz Dzieniak's user avatar

1
2 3 4 5
55