I added classes to Django app model to create mysql tables. I have 'downloads' table, and 'downloads' column in 'songs' table.
When i want to sync db, Django returns me error:
CommandError: One or more models did not validate:
mp3mid.downloads: Reverse query name for field 'song' clashes with field 'songs.downloads'. Add a related_name argument to the definition for 'song'.
Why it's impossible to give same name to table and column?
this is my models.py:
from django_evolution.mutations import *
from django.db import models
class singers(models.Model):
name = models.CharField(max_length = 255)
category = models.ForeignKey(categories)
class songs(models.Model):
name = models.CharField(max_length = 255)
singer = models.ForeignKey(singers)
downloads = models.IntegerField(max_length = 11)
exclusive = models.BooleanField(default = 0)
hit = models.BooleanField(default = 0)
date = models.DateTimeField(auto_now_add = True)
link = models.CharField(max_length = 255)
class downloads(models.Model):
song = models.ForeignKey(songs)
date = models.DateTimeField(auto_now_add = True)
Django allows you to make queries that span relationships.
In your case, the foreign key from downloads to songs means you could usually make queries that follow the relationship backwards from song to downloads:
from datetime import datetime
# fetch all songs with a download with a date on or after 2013-05-01.
songs = song.objects.filter(downloads__date__gte=datetime(2013,5,1))
However, you can't do that in this case, because downloads clashes with your songs.downloads field.
You have a couple of options. First, you can set related_name for your foreign key, as suggested by your error message.
class downloads(models.Model):
song = models.ForeignKey(songs, related_name="related_downloads")
Or, you can rename your song.downloads field.
class songs(models.Model):
...
num_downloads = models.IntegerField(max_length = 11)
As an aside, I recommend you rename your models to Singer, Song and Download (capitalized, singular instead of plural), to follow the Django convention.
Related
Here is the model
class Student(models.Model):
"""Student info"""
id = models.CharField( max_length=7,primary_key=True)
name = models.CharField(_('name'),max_length=8, default=""); # help_text will locate after the field
address = models.CharField(_('address'),max_length=30,blank=True,default="") #blank true means the
GENDER_CHOICES = [("M", _("male")),("F",_("female"))]
student_number = models.CharField(max_length=10,blank=True)
gender = models.CharField(_("gender"),max_length=6, choices = GENDER_CHOICES, default="M");
I user shell to create two users as below:
But the queryset number didn't increase although I created two users.
#I hate Django. Q = Q
You are using a custom id field as model id and you put it as Char, so you should add this id also when you want to save an object
But it is not a good idea, if you want to use custom id use it in this way
id = models.AutoField(primary_key=True)
I'm trying to replace a field in an intermediate table with a generic field. Using Django 1.6, MariaDB/MySQL.
I have a class (PermissionGroup) that links a resource to a group. Works fine. However I have several other tables that are similar - linking some id to a group id.
I thought I could replace these tables with one table that uses a generic foreign key, along with the group id. However this does not validate.
Here's the original, which works:
# core/models.py
class PermissionGroup(models.Model):
resource = models.ForeignKey('core.Resource')
group = models.ForeignKey('auth.Group')
class Resource(models.Model):
groups = models.ManyToManyField('auth.Group', through='core.PermissionGroup')
# auth/models.py
class Group(models.Model):
name = models.CharField(max_length=80, unique=True)
Now, trying to change the PermissionGroup to use a GenericForeignKey:
# core/models.py
class PermissionGroup(models.Model):
content_type = models.ForeignKey('contenttypes.ContentType')
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
group = models.ForeignKey('auth.Group')
class Resource(models.Model):
groups = models.ManyToManyField('auth.Group', through='core.PermissionGroup')
# auth/models.py
class Group(models.Model):
name = models.CharField(max_length=80, unique=True)
The django model validation now fails with:
core.resource: 'groups' is a manually-defined m2m relation through model PermissionGroup, which does not have foreign keys to Group and Resource
Is this simply not possible, or is another means to accomplish this?
I've been looking at the docs for search_fields in django admin in the attempt to allow searching of related fields.
So, here are some of my models.
# models.py
class Team(models.Model):
name = models.CharField(max_length=255)
class AgeGroup(models.Model):
group = models.CharField(max_length=255)
class Runner(models.Model):
"""
Model for the runner holding a course record.
"""
name = models.CharField(max_length=100)
agegroup = models.ForeignKey(AgeGroup)
team = models.ForeignKey(Team, blank=True, null=True)
class Result(models.Model):
"""
Model for the results of records.
"""
runner = models.ForeignKey(Runner)
year = models.IntegerField(_("Year"))
time = models.CharField(_("Time"), max_length=8)
class YearRecord(models.Model):
"""
Model for storing the course records of a year.
"""
result = models.ForeignKey(Result)
year = models.IntegerField()
What I'd like is for the YearRecord admin to be able to search for the team which a runner belongs to. However as soon as I attempt to add the Runner FK relationship to the search fields I get an error on searches; TypeError: Related Field got invalid lookup: icontains
So, here is the admin setup where I'd like to be able to search through the relationships. I'm sure this matches the docs, but am I misunderstanding something here? Can this be resolved & the result__runner be extended to the team field of the Runner model?
# admin.py
class YearRecordAdmin(admin.ModelAdmin):
model = YearRecord
list_display = ('result', 'get_agegroup', 'get_team', 'year')
search_fields = ['result__runner', 'year']
def get_team(self, obj):
return obj.result.runner.team
get_team.short_description = _("Team")
def get_agegroup(self, obj):
return obj.result.runner.agegroup
get_agegroup.short_description = _("Age group")
The documentation reads:
These fields should be some kind of text field, such as CharField or TextField.
so you should use 'result__runner__team__name'.
I am new to peewee, so please forgive me if this is a stupid question. I have searched on Google and in the peewee cookbook, but found no solution so far.
So, I have the following models to four of my DB tables:
class games_def(Model):
id = PrimaryKeyField()
name = TextField()
class Meta:
database = dbmgr.DB
class users_def(Model):
id = PrimaryKeyField()
first_name = TextField()
last_name = TextField()
class Meta:
database = dbmgr.DB
class sessions(Model):
id = PrimaryKeyField()
game = ForeignKeyField(games_def, related_name = 'sessions')
user = ForeignKeyField(users_def, related_name = 'sessions')
comment = TextField()
class Meta:
database = dbmgr.DB
class world_states(Model):
session = ForeignKeyField(sessions)
time_step = IntegerField()
world_state = TextField()
class Meta:
database = dbmgr.DB
Using these models I connect to an SQLite3 DB via peewee, which works fine.
After the connection has been established I do the following in my main Python code:
models.world_states.create(session = 1, time_step = 1)
However, this gives me the following error:
sqlite3.OperationalError: table world_states has no column named session_id
That is basically correct, the table world_state does indeed not contain such a column.
However, I cannot find any reference to "session_id" in my code at all.
Whe does peewee want to use that "session_id" colum name?
Do I miss something essentially here?
When you specify a ForeignKeyField() peewee expects to use a column ending in _id based on their own name. Your wold_states.session field thus results in an column named session_id.
You can override this by setting db_column for that field:
class world_states(Model):
session = ForeignKeyField(sessions, db_column='session')
I have two simple models in my Django app. Here's what they look like:
class Host(models.Model):
url = models.URLField(max_length= 200)
ssl = models.BooleanField(default = False)
class Query(models.Model):
host = models.ForeignKey(Host)
date = models.DateTimeField(auto_now_add = True)
latency = models.FloatField(null = True)
success = models.BooleanField(default = False)
error = models.CharField(max_length= 2000, null = True)
When i access the Host model, I only have access to the two fields url and ssl. When querying the Host model, I would like three extra fields to computed and returned dyanmicaly. These are the average_latency which would be the average of the not-null latency field of all the child Query records so i can access it something like this:
t = Tracker.objects.get(id = 1)
t.url
t.average_latency
Could someone please explain how I can do this or point me to some examples/documentation?
Thank you.
You can just use class properties:
class Host(models.Model):
.
.
.
#property
def average_latency(self):
# calculate latency from Query model ...
return latency
Bear in mind that this is a read-only property.
You can check django-denorm, it's pretty much about what you're trying to achievie. I also have some flashbacks that there are other similar django apps.