Using 'old' database with django

I'm using a hand built (Postgres) database with Django. With "inspectdb" I was able to automatically create a model for it. The problem is that some tables have multiple primary keys (for many-to-many relations) and they are not accessible via Django.

What's the best way to access these tables?


Asked by: Sawyer270 | Posted: 30-11-2021






Answer 1

There is no way to use composite primary keys in Django's ORM as of now (up to v1.0.2).

I can only think of three solutions/workarounds:

  1. There is a fork of django with a composite pk patch at github that you might want to try.
  2. You could use SQLAlchemy together with Django.
  3. You have to add a single field primary key field to those tables.

Answered by: Clark346 | Posted: 01-01-2022



Answer 2

Django does have support for many-to-many relationships. If you want to use a helper table to manage this relationships, the ManyToManyField takes a through argument which specifies the table to use. You can't model anything terribly complex this way, but it is good for most simple applications.

Answered by: Julia408 | Posted: 01-01-2022



Similar questions

python - How do I test a django database schema?

I want to write tests that can show whether or not the database is in sync with my models.py file. Actually I have already written them, only to find out that django creates a new database each time the tests are run based on the models.py file. Is there any way I can make the models.py test use the existing database schema? The one that's in mysql/postgresql, and not the one that's in /myapp/models.py ?


python - Using Django database layer outside of Django?

I've got a nice database I've created in Django, and I'd like to interface with through some python scripts outside of my website stuff, so I'm curious if it's possible to use the Django database API outside of a Django site, and if so does anyone have any info on how it can be done? Google hasn't yielded many hits for this.


python - Django database - how to add this column in raw SQL

Suppose I have my models set up already. class books(models.Model): title = models.CharField... ISBN = models.Integer... What if I want to add this column to my table? user = models.ForeignKey(User, unique=True) How would I write the raw SQL in my database so that this column works?


python - How do I do this Database Model in Django?

Django currently does not support the "Point" datatype in MySQL. That's why I created my own. class PointField(models.Field): def db_type(self): return 'Point' class Tag(models.Model): user = models.ForeignKey(User) utm = PointField() As you can see, this works, and syncdb creates the model fine. However, my current code calculates a length between...


python - Django script add field to database

I added a slug field to my database and now need to go through and add those. I want to run a script that looks at the slug field in the database and if empty generates and saves. Here is what I thought was along the lines, but is not working. from project.apps.tracks.models import * def process_slug(): if not track.slug: slug = slugify("%s - %s" % (track.name, track.artist)) else: ...


python - Django with huge mysql database

What would be the best way to import multi-million record csv files into django. Currently using python csv module, it takes 2-4 days for it process 1 million record file. It does some checking if the record already exists, and few others. Can this process be achieved to execute in few hours. Can memcache be used somehow. Update: There are django ManyToManyField fields that get processed as...


python - django eyed3 script to add mp3 to database

I'm writing a script to add a genre artist and title of song to django project. Here are parts from my models class GenreManager(models.Manager): def isGenreInDb(self,genre): try: genre=self.get(name__iexact=genre) return genre.id except Genre.DoesNotExist: return False def addGenreToDb(self,genre): new=Genre(name=genre) new.save() ...


python - How can I specify a database for Django Tests to use instead of having it build it every time?

I want to be able to use an existing test database to run my tests against and not have Django create and delete a database every time I want to run the tests. Is this possible?


python - Django find oldest entry in database

Looking for a way in a Django view to find the oldest entry in the database. Then take that value and to a time since. There has to be a simple way to do this with writing a complicated query.


python - How can I do INNER JOIN in Django in legacy database?

Sorry for probably simple question but I'm a newby in Django and really confused. I have an ugly legacy tables that I can not change. It has 2 tables: class Salespersons(models.Model): id = models.IntegerField(unique=True, primary_key=True) xsin = models.IntegerField() name = models.CharField(max_length=200) surname = models.CharField(max_length=200) class St...


python - Doing database JOIN in django

I want to do equivalent query as SELECT user_name, item_name FROM users, items WHERE users.favor_item_id = items.item_id, which is to return user_name and item_name pairs. In the database, one user can have multiple favoured items. I'm just curious what is a equivalent Django query for this SQL query?? My first thought is to list all (user, favor_item_id) pair from USERS, and then look for item...


python - Django search in the database

I use MySQL for the production server and SQLite for the testing local server for my django application. I've a model like this: class Product(models.Model): name = models.CharField(max_length = 40) I've implemented a search feature in my application for searching product. I use this command: Product.objects.filter(name__contains = text) But in this way, if...


python - Can Rails & Django (now) query more than one database at a time?

EDIT: Since you are asking for specifics, consider a photo-sharing site (like Flickr or picasa - - I know that one uses PHP, while the other uses Python) for instance. If it proves to be successful, it needs to scale enormously. I hope this is specific enough. It's been sometime since I heard any discussion on this, and since I am in the decision making process of choosing between Ruby and...


python - MySQL database being hit too many times with django query

I'm using django-favorites to pull the list of objects faved by a user. The app has a model and a manager class FavoriteManager(models.Manager): """ A Manager for Favorites """ def favorites_for_user(self, user): """ Returns Favorites for a specific user """ return self.get_query_set().filter(user=user) class Favorite(models.Model): user = models.ForeignKey(User) ...


python - Django Database Query

I have a Model in Django. It has a Group and inside the group are Cameras. class Groups(models.Model): groupName = models.CharField(max_length=255) class Cameras(models.Model): group = models.ForeignKey(Groups) cameraID = models.IntegerField() When I try to remove a Camera or set of cameras in the model. camera = Cameras.objects.filter(cameraID=int(camID)) cam...


python - Django database router

I'd like to route (change) the database based on the authenticated user. I've looked at the docs but I don't know how to do this upon user login... I was thinking of adding a field with database_name to my custom UserProfile and then I'd like to pass this info to the database router which woul...


python - django unable to open database file

i am implementing a django web site, the site goes to the hello world view: http://ec2-107-20-20-19.compute-1.amazonaws.com/ views.py /home/ubuntu/djangoProj/micopiloto/portfolio # Create your views here. from django.http import HttpResponse def view(r...


python - How to log django app to database

I just wanna ask how to log all the things that is happening to my app in django. I didn't use the django admin. Instead I create an app for login and an app for my blog,comment,like/dislike. How can I log all these, like how many time this user logs in in my website and how many hours he/she stays. How many times she/he comment or like. Is this possible?


python - django - allow user to set something in database

I want to let user change language of a site by click on a country flag. In my models.py file i have: class RegularUser(models.Model): (...) language = models.CharField(max_length = 10, null=True, blank=True, choices=[(a, _(b)) for (a,b) in settings.LANGUAGES], verbose_name=_("Language")) I also made there a function: def set_language(self, new_lang): ...


python - Django post time to database

I'm new to Django and trying to build a blog that will register the time the user logged in and the time the user logged out. I'm guessing this would go in the views but I don't have a clue on how to approach the problem. How would I go about sending the time the user logged in to the database? Any hint and guidance will be appreciated.


python - Sometimes can't delete an Oracle database row using Django

I have a unit test which contains the following line of code Site.objects.get(name="UnitTest").delete() and this has worked just fine until now. However, that statement is currently hanging. It'll sit there forever trying to execute the delete. If I just say print Site.objects.get(name="UnitTest") then it works, so I know that it can retrieve the site. ...


python - How do I test a django database schema?

I want to write tests that can show whether or not the database is in sync with my models.py file. Actually I have already written them, only to find out that django creates a new database each time the tests are run based on the models.py file. Is there any way I can make the models.py test use the existing database schema? The one that's in mysql/postgresql, and not the one that's in /myapp/models.py ?


python - Using user input to find information in a Mysql database

I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. I am a bit stuck on how to get started. Does anyone have any tips for me?


python - Import XML into SQL database

I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? I know this ability is built into MySQL 6.0, but that is not an option right now because it is an alpha development rel...


database - python orm

This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conversion (if the app is live)? So, I start with a basic Phone app Object person: name, address, city, s...


python - Large Sqlite database search

How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)? I'm using Python and SQLObject ORM: import re ... def search1(): cr = re.compile(ur'foo') for item in Item.select(): if cr.search(item.name) or cr.search(item.skim): print item.name This function runs in more than 30 seconds. How sh...


abap - Query SAP database from Python?

Closed. This question needs details or clarity. It ...


A database for python 3?

I'm coding a small piece of server software for the personal use of several users. Not hundreds, not thousands, but perhaps 3-10 at a time. Since it's a threaded server, SQLite doesn't work. It complains about threads like this: ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140735085562848 and this is thread id 43...


python - URLs stored in database for Django site

I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py. Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... so on, so on. I also have a column for the URL. How do I get Django to call the information in...


python - Using Django database layer outside of Django?

I've got a nice database I've created in Django, and I'd like to interface with through some python scripts outside of my website stuff, so I'm curious if it's possible to use the Django database API outside of a Django site, and if so does anyone have any info on how it can be done? Google hasn't yielded many hits for this.


database - Problem opening berkeley db in python

I have problems opening a berkeley db in python using bdtables. As bdtables is used by the library I am using to access the database, I need it to work. The problem seems to be that the db environment I am trying to open (I got a copy of the database to open), is version 4.4 while libdb is version 4.6. I get the following error using bsddb.dbtables.bsdTableDB([dbname],[folder]): (-30972, "DB_VERSION...


database - Store simple user settings in Python

I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue. The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them. For example, userdb["bob"]["colour_scheme"] would have the value "b...


python - Sometimes can't delete an Oracle database row using Django

I have a unit test which contains the following line of code Site.objects.get(name="UnitTest").delete() and this has worked just fine until now. However, that statement is currently hanging. It'll sit there forever trying to execute the delete. If I just say print Site.objects.get(name="UnitTest") then it works, so I know that it can retrieve the site. ...


python - How do I test a django database schema?

I want to write tests that can show whether or not the database is in sync with my models.py file. Actually I have already written them, only to find out that django creates a new database each time the tests are run based on the models.py file. Is there any way I can make the models.py test use the existing database schema? The one that's in mysql/postgresql, and not the one that's in /myapp/models.py ?


python - Using user input to find information in a Mysql database

I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. I am a bit stuck on how to get started. Does anyone have any tips for me?


python - Given an rpm package name, query the yum database for updates

I was imagining a 3-line Python script to do this but the yum Python API is impenetrable. Is this even possible? Is writing a wrapper for 'yum list package-name' the only way to do this?


python - Import XML into SQL database

I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? I know this ability is built into MySQL 6.0, but that is not an option right now because it is an alpha development rel...


python - How do I notify a process of an SQLite database change done in a different process?

Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database. An "editor" process is any editor for that database: it changes the database constantly. Now I want the player t...


database - python orm

This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conversion (if the app is live)? So, I start with a basic Phone app Object person: name, address, city, s...


python - Large Sqlite database search

How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)? I'm using Python and SQLObject ORM: import re ... def search1(): cr = re.compile(ur'foo') for item in Item.select(): if cr.search(item.name) or cr.search(item.skim): print item.name This function runs in more than 30 seconds. How sh...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top