Django - PostgreSQL doesn't match default attribute - django

I have the following model at Django:
class Community(models.Model):
name = models.CharField(max_length=255)
members = models.ManyToManyField(User, through='Membership')
date_created = models.DateTimeField(auto_now_add=True)
But when I check the structure of the table (using Postico for PostgreSQL) the field of date_created after applying the migrations shows no default.
I have also tried with explicitly default=date.today() but it does not work.
Any ideas what I am missing?
Thanks,
Pablo
EDIT
Great thanks to this post: How to make a script to insert data in my default sqlite3 database django
I was trying to populate the database via script using PostgreSQL driver, when it is way simpler importing the Django models a use the create method (also thanks to Daniel Roseman in the comments that led me find the post).

Related

Django rest framework api with existing mysql database

How can I create a Django REST Framework API that connects to an already existing MySQL tables instead of creating them through modela.py. My models.py shows something like this:
class Author(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __str__(self):
return f'{self.first_name} {self.last_name}'
Instead of this, I need to take data directly from existing tables in MySQL.
For that you need to define same class name as your table name with meta char field
like for example
RandomTable(id INT(10),name varchar(10)) is your existing mysql table then the models.py for it will be
class AppnameRandomTable(models.Model)
id = models.CharField(db_column="id") #name of column of existing db
inside that you will need to write the fields of your existing table name in meta section
class Meta:
db_table = "RandomTable" #your existing mysql table name
time saving hack just create a class in models.py and on terminal run "python manage.py inspectdb" you will automatically get all the column names from there.
You can just copy and paste names from there , because for reading and writing on columns you need to define their variables in your class even if the table is existing mysql table
python manage.py inspectdb > models.py
If you run that command it will create a models.py in the project's root directory. Once you've done that you can either move it directly into the project or create a models folder and break it down into areas of concern from there. You will likely have to do the work of adding related_name = 'foo' to a lot of fields that have relationships with other models. That can be time-consuming but it works.

Django - How can Django ORM manage user's uploaded tables in database

My web application allow users to load/create tables in the Postgres database. I know Django ORM needs a model definition in models.py for each table in the database to access it. How can I access the user's uploaded tables in the app without creating a new model definition on the fly each time a new table is uploaded? I was thinking about creating a generic model definition that decompose the table into its components like this:
models.py
class Table(models.Model):
filename = models.CharField(max_length=255)
class Attribute(models.Model):
table = models.ForeignKey(Table)
name = models.CharField(max_length=255)
type = models.IntegerField()
width = models.IntegerField()
precision = models.IntegerField()
class Row(models.Model):
table = models.ForeignKey(Table)
class AttributeValue(models.Model):
row = models.ForeignKey(Row)
attribute = models.ForeignKey(Attribute)
value = models.CharField(max_length=255, blank=True, null=True)
The problems with such a generic model is that every tables are mixed in 4 table (not useful in admin interface) and its really slow to create when you have a lot of rows. Do you have suggestion with this case?
Edit: Could it be viable to use a separate database to store those tables and use a router and manage.py inspectdb to update its models.py each time a user add or delete a table? (like in this post) I wonder what would happen if two users add a table in the same time?
I think you should look into dynamic models like here:
https://code.djangoproject.com/wiki/DynamicModels
or here:
http://dynamic-models.readthedocs.org/en/latest/
Good luck because its not an easy way my friend :)
You'll probably need to use raw SQL queries for doing this.
If the schema of the tables you are expecting are predefined you can use a database router to link some model to a specific table name for each user.

Django ManyToMany Through not syncing or migrating

I have this model (truncated here for brevity):
class Meal(models.Model):
host = models.ForeignKey(User, related_name="cooking")
cost = models.IntegerField(default=1)
summary = models.CharField(max_length=1024, default="A good dinner")
diners = models.ManyToManyField(User, through='Attendance',
related_name="diners", blank=True)
When I sync it, the diners Field is completely ignored. It doesn't appear in the database and there is no error when running syncdb. It's as if it's not there. The User and Attendance tables are all fine.
I discovered this problem when trying to add this field with South, so I've tried that as an alternative too.
Any ideas?
Thanks
Did you already run syncdb fyrir Meal before you added the diners field?
Because syncdb will not alter existing tables as you can read here:
Django docs
Side note - I have not used south personally but I have used Django evolution while developing.
Edit:
After reading your comment I think I know what the problem is.
When using through with ManyToManyField Django doesn't add a field to that table, all the necessary information is in the attendance table.

How does unique_together work in Django-nonrel?

I am using django-nonrel and django-mongodb engine.
In engine's documentation, it says that it supports django's Meta options.
I tried using unique_together in a model as such:
class Bottler(models.Model):
location = models.CharField(max_length=20)
source = models.CharField(max_length=20)
transactionID = models.CharField()
class Meta:
unique_together = (("location","source"),)
However this doesn't seem to have worked since I could create duplicates without any error being raised.
I know unique_together is enforced at the database level.
What does that translate to in MongoDB?
Do I have to validate it manually?
You need to run syncdb in order to sync database indices.
Somehow syncbd will not update your indexes in mongodb. What you can try (if possible in your situation) is to delete the collection and then run syncdb. In my case it did create the indexes then.

Django admin - instance needs to have a primary key value before a many-to-many relationship can be used

edit: I wasn't clear before, I am saving my object in the django admin panel, not in a view. Even when I save the object with no many-to-many relationships I still get the error.
I have a model called TogglDetails that has a ForeignKey relationship with the standard django User model and a MayToManyField relationship with a model named Tag. I have registered my models with django admin but when I try to save a TogglDetails instance I get the error in the title.
Here are my models:
class Tag(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class TogglDetails(models.Model):
token = models.CharField(max_length=100)
user = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, blank=True, null=True)
def __unicode__(self):
return self.user.username
class Meta:
verbose_name_plural = "toggl details"
As far as I can tell, there should be no issues with my models and django admin should just save the instance without any issues. Is there something obvious that I have missed?
I am using Django 1.3
The answer to my question was this: Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db.
As stated by other users:
Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db
In addition:
This is most likely caused by a backwards incompatible change that renders some primary key types in custom models beyond reach for Django 1.3. See Django trac tickets https://code.djangoproject.com/ticket/13295 and http://code.djangoproject.com/ticket/15682 for more information.
I solved the problem by running the follow commands for the affected tables/sequences.
Specifically running the command:
manage.py dbshell
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
change tablename_colname_seq and tablename.colname
Don't let us guess and add the Error message to your question, this gives most information about where it fails.
Have you imported the User model?
from django.contrib.auth.models import User
I've had this problem as well and the only thing I could do was make the M2M fields blank and not set them until I hit Save and Continue Editing.
I think this just may be a framework wart, as you will notice the User section of the Admin site also has a very strict "You can only edit these fields until you save the model".
So my recommendation is to adopt that scheme, and hide the M2M form field until the model has a Primary Key.
I tried Django 1.3 using CPython, with different database setups. I copy-pasted the models from the question, and did some changes: first I added
from django.contrib.auth.models import User
at the top of the file and I put the reference to Tag between quotes. That shouldn't make any difference. Further, I created the following admin.py:
from django.contrib import admin
import models
admin.site.register(models.Tag)
admin.site.register(models.TogglDetails)
For Sqlite3, the problem described doesn't occur, neither for MySQL. So I tried PostgreSQL, with the postgresql_psycopg2 back end. Same thing: I can't reproduce the error.
So as far as I can figure, there's nothing wrong with the code in the question. The problem must be elsewhere.