I am curious about Django database model pk.
Is there any difference this
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=50)
between this?
class Category(models.Model):
category_name = models.CharField(max_length=50)
Are the same things AutoField with primary_key and default pk?
Yes, the difference is, the column name in the database for the primary key is category_id and in the second case is id.
One way you can make the second example emulate the first one is:
class Category(models.Model):
category_name = models.CharField(max_length=50)
#property
def category_id(self):
return self.id
From the documentation,
AutoField
An IntegerField that automatically increments according to available IDs. You usually won’t need to use this directly; a primary key field will automatically be added to your model if you don’t specify otherwise
The difference is field name.
For example, I definded the model "Category" with the field "category_id":
# "myapp/models.py"
from django.db import models
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=50)
Then, run this command below:
python manage.py makemigrations && python manage.py migrate
Now, I opened "db.sqlite3" then the field name is "category_id":
Next, I definded the model "Category" without the field "category_id":
# "myapp/models.py"
from django.db import models
class Category(models.Model):
category_name = models.CharField(max_length=50)
Then, run this command below:
python manage.py makemigrations && python manage.py migrate
Now, I opened "db.sqlite3" then the field name is "id":
Related
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,
)
I have issues when I'm trying to execute the following code at Ubuntu terminal:
$ python manage.py makemigrations
I need to add a field called 'album' in my class named music, like that:
models.py file
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Music(models.Model):
class Meta:
db_table = 'music'
title = models.CharField(max_length=200)
seconds = models.IntegerField()
album = models.ForeignKey('Album', related_name='musics')
def __str__(self):
return self.title
class Album(models.Model):
class Meta:
db_table = 'album'
title = models.CharField(max_length=200)
band = models.ForeignKey('Band', related_name='albuns')
date = models.DateField()
serializers.py file
from rest_framework import serializers
from .models import Music, Band, Album, Member
class MusicSerializer(serializers.ModelSerializer):
class Meta:
model = Music
fields = '__all__'
class BandSerializer(serializers.ModelSerializer):
class Meta:
model = Band
fields = '__all__'
My error obtained:
(music) leonardo.oliveira#dss-skinner:~/django_music/myapi$ python manage.py makemigrations
You are trying to add a non-nullable field 'album' to music without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 2
What is happening here is, It is trying to add an album field in music model. According to defination of this field
album = models.ForeignKey('Album', related_name='musics')
it is a non-nullable field. instant fix would be
album = models.ForeignKey('Album', related_name='musics', null=True)
but if you want to add a default album for this field you can add a default by doing something like this.
album = models.ForeignKey('Album', related_name='musics', default=Album.objects.first())
but for this to work you should have atleast one album present in DB.
After doing these changes you run
python manage.py migrate
I'm new to Django and I have this problem: I want to create a simple web site where I display and work through the views objects Album and Artist. I changed the relationship
class Album(models.Model):
...
songs_of_album = models.ManyToManyField('Song')
class Song(models.Model):
name = models.CharField(max_length=150)
in my current models.py file
from django.db import models
from django.utils import timezone
class Album(models.Model):
name = models.CharField(max_length=150,default='')
artist = models.CharField(max_length=150,null=False,blank=False)
year = models.IntegerField(default=timezone.now().year)
genre = models.ForeignKey('Genre',blank=False)
vote = models.IntegerField(blank=True,null=True)
def __str__(self):
return self.name
class Song(models.Model):
name = models.CharField(max_length=150,null=False,blank=False)
album_name = models.ForeignKey('Album')
artist = models.ForeignKey('Artist')
def __str__(self):
return self.name
class Artist(models.Model):
name = models.CharField(max_length=150,primary_key=True)
def __str__(self):
return self.name
class Genre(models.Model):
name = models.CharField(max_length=150,primary_key=True)
def __str__(self):
return self.name
I want to know two things:
if my models.py is written right and the relationship that exists between the class and Album Artist
Now when I run the command python manage.py makemigrations gives me this error You are trying to add a non-nullable field 'id' to album without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:
I have read many posts similar but they are not able to find the solution.
I hope you can help me. Thank you
You changed m2m relationship to one2many, all is ok, but you need change your related database tables and you must migrate your db to new style, if you have any data on db set null=True for album_name attribute of Song class, and if your db is empty, delete all file in migrations folder of your app except __init__.py file, and then run two below commands:
python manage.py makemigrations
And then:
python manage.py migrate
travelers.models
from django.db import models
class ShortInfoTraveler(models.Model):
name = models.CharField(max_length=200, blank=True)
email = models.EmailField(blank=True)
blogs.models
from django.db import models
from travelers.models import ShortInfoTraveler
class Title(models.Model):
shortinfotraveler = models.ForeignKey('ShortInfoTraveler')
title_text = models.CharField(max_length=255)
description = models.CharField(max_length=255, null=True, blank=True)
And When I run makemigrations, Terminal show following-
ERRORS: blogs.Title.shortinfotraveler: (fields.E300) Field defines a relation with
model 'blogs.ShortInfoTraveler', which is either not installed, or is abstract.
You should be setting your foreign key like this:
models.ForeignKey('travelers.ShortInfoTraveler')
If you want to use a string to set the foreign key relation.
Or you should just set ShortInfoTraveler without it being a string since you've imported it.
Setting it to "ShortInfoTraveler" is looking for the model in the current models file instead of your other app which you can see in the error message output back.
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