I'm running a command to dump my database contents into json format:
python manage.py dumpdata <appname>.<modelname> > file.json
However, it is not dumping my many-to-many field which is called category_id. Well in fact, it is dumping it but the field is consistently empty. Why??
I have tried calling that table directly (which is a category mapping) as such:
python manage.py dumpdata <appname>.<modelname_category_id> > file.json
and I get the following error:
Error: Unable to serialize database: Category matching query does not exist.
I'm using Django 1.2.1 and SQLite backend.
Any hints?
UPDATE: I have tried deleting all rows in the modelname.category_id table, and even with only one row I still get this error.
The table is defined as follows
id: integer PRIMARY KEY
unipart_id: integer
category_id: integer
and both unipart_id and category_id fields are valid and exist.
I have two tables like below,
from django.db import models
class AggregationCategories(models.Model):
name = models.CharField(max_length=50)
class Meta:
db_table = "AggregationCategories"
class AggregationFunctions(models.Model):
name = models.CharField(max_length=50)
aggregation_category = models.ManyToManyField(
AggregationCategories,
related_name='aggregationfunctions_aggregationcategories'
)
class Meta:
db_table = "AggregationFunctions"
When you create many-to-many relationships, you'll get additional table the structure of <model name>_<filed name>. So according to my example model name is AggregationFunctions and the field name is aggregation_category. Based on that my additional table should be AggregationFunctions_aggregation_category. Yes, you can see all three tables in below picture.
So you can dump the data in third table like this, python manage.py dumpdata <app name>.<third table name>. So my app name is catalogue and the third table name is AggregationFunctions_aggregation_category. Based on that my command should be,
python manage.py dumpdata catalogue.AggregationFunctions_aggregation_category
If you've created many-to-many table using ManyToManyField.through, ManyToManyField.through_fields, for an example (directly took it from Django Official Documentation),
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=50)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(
Person,
through='Membership',
through_fields=('group', 'person'),
)
class Membership(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
inviter = models.ForeignKey(
Person,
on_delete=models.CASCADE,
related_name="membership_invites",
)
invite_reason = models.CharField(max_length=64)
Now you have a class call Membership for your many-to-many relationship, so you can use it same as before like this,
python manage.py dumpdata catalogue.Membership
My solution:
appname.modelname_id_category
Dump the data from the third table in a m2m relationship. Its name is myapp_model1_model2.
python manage.py dumpdata myapp.model1_model2 --indent 4 > fixtures/filename.json
Ran into this topic as I was searching how to dump m2m site values from a table and nailed it. I'm on Django 4.
class MyModel(models.Model)
title = models.CharField()
sites = models.ManyToManyField(Site)
...
David's suggestion helped me find:
manage.py dumpdata --format json appname.MyModel_sites
Related
After splitting a models.py file containing 3 models, into 3 different files, I got the following error when running make migrations or migrate:
(models.E022) .resolve_through_model at
0x105d74e18> contains a lazy reference to products.itemsbyarticle, but
app 'products' doesn't provide model 'itemsbyarticle'.
products.Article.items: (fields.E331) Field specifies a many-to-many
relation through model 'ItemsByArticle', which has not been installed.
Project structure is: my_project > products > models > [article.py | item.py | items_by_article.py]
article.py
class Article(models.Model):
items = models.ManyToManyField('products.Item', through='ItemsByArticle', blank=True,
verbose_name=_('items'))
NOTE: I tried through='products.ItemsByArticle' instead, same error.
item.py
class Item(models.Model):
# ...
items_by_article.py
class ItemsByArticle(models.Model):
class Meta:
unique_together = ('article', 'item')
article = models.ForeignKey('products.Article',
on_delete=models.CASCADE)
item = models.ForeignKey('products.Item',
on_delete=models.CASCADE,
verbose_name=_('item'))
Curiously, when running unit tests (and Django creates a new database), there is no error.
Do you have __init__.py file in my_project/products/models/ which imports all models of the module?
from .article import Article
from .item import Item
from .items_by_article import ItemsByArticle
My English is poor, sorry
This is my struct:
bookstore
---author(app1)
---book(app2)
Or in code:
from django.db import models
from author.models import Profile
from django.contrib import admin
class Book(models.Model):
title = models.CharField(max_length = 150)
page = models.IntegerField()
price = models.IntegerField()
author = models.ForeignKey(
'Profile',
on_delete=models.CASCADE,)
publish_date = models.DateField()
class Meta(object):
db_table = "book"
class BookAdmin(admin.ModelAdmin):
pass
admin.site.register(Book, BookAdmin)
mysql have some data, now I want to use them to show my web, not to do that creat data in database. Thank you guys!
I have a question:
My Django == 1.9 , python == 3 , windows10
I want to use mysql (my database contect is really do it).
When I find some resource, I will see that
python manage.py sql [appname] it is Django to SQL
when I want to use Django to mysql.
Can I use python manage.py inspectdb? It will have a models.py
python manage.py sql [appname] = python manage.py inspectdb?
ERRORS:
book.Book.author: (fields.E300) Field defines a relation with model 'Profile', which is either not installed, or is abstract.
book.Book.author: (fields.E307) The field book.Book.author was declared with a lazy reference to 'book.profile', but app 'book' doesn't provide model 'profile'.
In your Book model, you refer with a field named author to a model Profile. Since that model is defined in another app, you should refer to it as app_name.ModelName, so likely that is:
class Book(models.Model):
title = models.CharField(max_length = 150)
page = models.IntegerField()
price = models.IntegerField()
author = models.ForeignKey(
'app1.Profile', # add name of the app
on_delete=models.CASCADE,
)
publish_date = models.DateField()
If you named this model Author however, as the question text (not the code), seems to suggest, you should use app1.Author. Of course you replace app1 with the real name of the app.
This is described in the documentation in the ForeignKey [Django-doc]:
To refer to models defined in another application, you can
explicitly specify a model with the full application label. For example, if the Manufacturer model above is defined in another
application called production, you’d need to use:
class Car(models.Model):
manufacturer = models.ForeignKey(
'production.Manufacturer',
on_delete=models.CASCADE,
)
If I have two models and one inherits from another and setup the database with migrate etc. like so:
class TemplateProduct(models.Model):
type = models.CharField(max_length=20)
class Product(TemplateProduct):
name = models.CharField(max_length=80)
Then how would I migrate the db to make it so that Product does not inherit from TemplateProduct? Say I just want these models instead:
class TemplateProduct(models.Model):
type = models.CharField(max_length=20)
class Product(models.Model):
name = models.CharField(max_length=80)
When I try to migrate this, I get the following error:
django.db.utils.ProgrammingError: column "templateproduct_ptr_id" of relation "product_product" does not exist
And then when I remove the delete "templateproduct_ptr_id" from the migration, I get the following error:
django.core.exceptions.FieldError: Local field u'id' in class 'Product' clashes with field of similar name from base class 'TemplateProduct'
As the title says: how do I migrate changes in Django when I'm uninheriting a model?
So my solution was to delete both models. Then python manage.py makemigrations --merge, then I added the models back the way I wanted them, finally running python manage.py makemigrations --merge again to add the models back in.
This may not be the most elegant solution but it worked.
I've been trying for a long while to migrate the sqlite database to a more stable postgresql since I am going into production. I've had some problems, but the one I've hit a roadblock and can't get any further.
To get the backup I ran ./manage.py dumpdata --exclude auth.permission --exclude contenttypes --natural-foreign > db.json with sqlite configured in settings.py.
Once the postgresql database was configured I ran a ./manage.py migrate with postgresql configured in settings.py.
Finally I ran ./manage.py loaddata db.json and got the following error:
django.db.utils.ProgrammingError: Problem installing fixture '/home/ubuntu/bl/loom/db.json': Could not load web.Project(pk=18): operator does not exist: character varying = integer
LINE 1: ...INNER JOIN "web_project_tags" ON ("web_tag"."tag" = "web_pro...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
The model(s) that the error is referring to has the following code:
class Project(models.Model):
owner = models.ForeignKey(User, related_name='owner')
name = models.CharField(max_length=50)
img = models.ImageField("Cover", upload_to="img/projects", blank=True, null=True)
vid = models.URLField("Youtube Link", null=True, blank=True)
desc = models.TextField("Description", max_length=500)
stakeholders = models.ManyToManyField(Profile, related_name='stakeholders', blank=True)
industry = models.ManyToManyField(Industry, related_name="industry")
tags = models.ManyToManyField(Tag, related_name="project_tag")
is_private = models.BooleanField("Is this a private project?", default=False, help_text="Private projects are not shown on the index.")
b_type = models.ForeignKey(B_type, help_text="What type of project is this")
role = models.ForeignKey(Role, related_name="role")
deleted = models.BooleanField(default=False)
def __unicode__(self):
return self.name
class Meta:
verbose_name = "Project"
verbose_name_plural = "Projects"
class Tag(models.Model):
tag = models.CharField("Tag", max_length=100, primary_key =True)
def __unicode__(self):
return self.tag
class Meta:
verbose_name = "Tag"
verbose_name_plural = "Tags"
Update:
The log file contains a more detailed error and it shows the full query.
2016-05-09 00:54:39 UTC ERROR: operator does not exist:
character varying = integer at character 89
2016-05-09 00:54:39 UTC HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
2016-05-09 00:54:39 UTC STATEMENT: SELECT "web_tag"."tag" FROM "web_tag" INNER JOIN "web_project_tags" ON ("web_tag"."tag" = "web_project_tags"."tag_id") WHERE "web_project_tags"."project_id" = 18
I finally solved the problem, hopefully this answer will help someone.
After checking the log I checked the postgresql database for the tables it was throwing an error. It turns out that web_project_tags had the wrong data type even though the migrations were done to the latest version. I corrected this data type using:
ALTER TABLE problematic_table ALTER COLUMN problematic_column TYPE character varying(100);
With this I ended up loading the data with ./manage.py loaddata db.jsonand no more errors.
A duplicate model field is giving me trouble (no such table appname_modelname when I run my webpage). Whenever I do ./manage.py migrate appname, it gives me "duplicate field". I checked my models.py, there is only one of them there. How do I delete that duplicate field? It seems no matter what I do, it stays. I've tried:
Deleting the database
Deleting migrations folder in app folder
Doing ./manage.py sqlclear south and then dropping the south_migrationhistory table in the dbshell
./manage.py schemamigration appname --initial, ./manage.py migrate appname --fake
I've run out of ideas.
class Document(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True, default=None)
identity = models.CharField(max_length=255, default=None, null=True)
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
docfile = models.FileField(upload_to=_upload_path, storage=fs) # upload_to is a path inside the storage path
def get_upload_path(self,filename):
return str(self.user.id) + '/' + str(date.today()) + '/' + filename
You can't do this, for your user foreign key, Django ORM will create a database field named user_id (your foreign key field name plus _id) to use it as a FK in the database.
You don't have to create this field yourself (the ORM will take care), even if you need it, change the name of the attribute user or user_id.
From the documentation:
Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.
Not sure but problem causing here in these two line
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
Better to use "related name" attribute to avoid the duplicate error as in database "user" will be added as user_id.
user = models.ForeignKey(User, related_name="id_user") # Change the related field as your convenience
user_id = models.IntegerField(null=True, related_name="user_id")
Check if this resolve your issues