error when i inherit from abstract models in django - django-models

First of all i have been reading a lot and i dont found the answer.
i have a django project and inside that project i have some apps, more especifically
DJANGO-PROJECT
*--------- app_base
*--------- app_equipment
*--------- app_customer
then app_base is the app for code that is common to the other apps, in my case i have a models.py file a class who has a class:
from django.db import models
from datetime import date
import project_name.utilies as ut
class BaseModel():
status = models.CharField( max_length = 1, choices = ut.STATUS_CHOICES, default = 1 )
created_date = models.DateField( default = date.today )
last_modified_date = models.DateField( null = True )
deleted_date = models.DateField( null = True )
createdby_id = models.IntegerField( default = 0 )
modifiedby_id = models.IntegerField( default = 0 )
class Meta:
abstract=True
then in app_equipment i have another models.py file and in that file i have the next class:
from django.db import models
from app_base.models import BaseModel
class Equipment(BaseModel):
name = models.CharField( max_length = 250 , default="")
image = models.CharField( max_length = 250 , default="" )
desc = models.TextField( default="")
horsepower = models.IntegerField( default = 0 )
fuelcapacity = models.IntegerField( default = 0 )
model = models.CharField( max_length = 250 , default="" )
year = models.IntegerField( default = 0 , )
purchasecost = models.IntegerField( default = 0 )
class Meta:
db_table = "equipment"
so equipment extends from BaseModel or that whats i read in django documentation the error is when i want to execute commmand makemigrations i get an error:
You are trying to add a non-nullable field 'id' to equipment 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
and i dont know how to solve it, i'been trying put id fields, and nothing happens, some people say the error is to clear, but what part of the diferents files and app is clear?
the error is solved when i dont inherit the abstract model, but i want to usea all those properties in BaseModel in each table of the others models
thanks in advance guys

Related

An error occurs when tries to add a model in django-admin. (many-to-many relations)

I want to connect with Product model and productcategory model with manytomany relation. When I write it like this.
class Product(models.Model):
id = models.CharField(primary_key=True, default=generateUUID(), max_length=36, unique=True, editable=False)
category = models.ManyToManyField('ProductCategory')
creatorid = models.ForeignKey('User', models.DO_NOTHING, db_column='creatorId', related_name='creator') # Field name made lowercase.
createdat = models.DateTimeField(db_column='createdAt', default=timezone.now) # Field name made lowercase.
updatedat = models.DateTimeField(db_column='updatedAt') # Field name made lowercase.
status = models.TextField(choices=PRODUCT_STATUS.choices) # This field type is a guess.
class Meta:
managed = False
db_table = 'product'
class ProductCategory(models.Model):
id = models.CharField(primary_key=True, default=generateUUID(), max_length=36, unique=True, editable=False)
name = models.TextField()
rootcategory = models.TextField(choices=PRODUCT_ROOT_CATEGORY.choices, blank=True, null=True, db_column='rootCategory') # Field name made lowercase. This field type is a guess.
icon = models.TextField()
class Meta:
managed = False
db_table = 'product_category'
When I try to add a product model in admin, the following error occurs. What's the problem?
Error ScreenShot

How to retrieve result data foreach in foreach on cakephp

I like to produce some universal function for my project
in a harcode php mode it would be like :
<select id="segment" name="segment">
<option value=''></option>
<?php
$sql = "select segment_id, segment_name, segment_parentid
from test_segment where segment_parentid = 'root' and segment_status = '1' order by segment_name asc";
$sql = $koneksi_db->sql_query($sql);
while($row = $koneksi_db->sql_fetchrow($sql)){
printf( "<option value=$row[segment_id] disabled>".ucwords($row['segment_name'])."</option>" );
$sql1 = "select segment_id, segment_name, segment_parentid from test_segment where convert(varchar, segment_id) <> 'root' and
segment_parentid= '$row[segment_id]' and segment_status = '1' order by segment_name asc";
$sql1 = $koneksi_db->sql_query($sql1);
while($row1 = $koneksi_db->sql_fetchrow($sql1)){
printf( "<option value=$row1[segment_id]> |_".ucwords($row1['segment_name'])."</option>" );
}
}
?>
</select>
How to convert that code into cakephp MVC method code? the Controller and Model
, I shall not to breaking MVC method with hardcode way for this code.
note : $koneksi_db->sql_query, $koneksi_db->sql_fetchrow was my own function for query process, and for query I cannot change into cakephp method, because it was restrict procedure from my mentor.
One way is to create a model representing the dataset you want. Then load the model for any controller that needs access to the data and that controller's view using that data in the in the select.
Step1: Create a MySQL view to represent the two SQL statements:
CREATE VIEW segments AS
SELECT segment_id, UPPER(segment_name), segment_parentid, UPPER(segment_name) AS sortfield
FROM test_segment
WHERE segment_parentid = 'root' AND segment_status = '1'
UNION
SELECT UPPER(test_segment.segment_id), test_segment.segment_name, test_segment.segment_parentid, UPPER(CONCAT(parent.segment_name, test_segment.segment_name))
FROM test_segment
JOIN test_segment AS parent
ON test_segment.segment_parentid = parent.segment_id
AND parent.segment_status = '1'
WHERE convert(varchar, test_segment.segment_id) <> 'root'
AND test_segment.segment_status = '1';
Step2: Create Model for this
<?php
App::uses('AppModel', 'Model');
class Segment extends AppModel {
// the name of the view
public $useTable = 'segment';
public $displayField = 'segment_name';
public $primaryKey = 'segment_id';
}
Step3: In whatever controller method you want this, Use this code
$this->loadModel('Segment');
$segments = $this->Segment->find('list', array('order => array('sortfield')));
set('segments', $segments);
Step4: Then in that controller's view, add the element (I'm assuming you will use the form helper, otherwise you can write the html out:
echo $this->Form->select('segments',$segments);

Appengine error object has no attribute '_key'

I have a GAE database entity that looks like this:
class Notification(db.Model):
alert = db.StringProperty()
type = db.StringProperty()
status = db.StringProperty(default="unread", choices=set(["unread", "read"]))
created = db.DateTimeProperty(auto_now_add=True)
modified = db.DateTimeProperty(auto_now=True)
entity = db.StringProperty()
record = db.ReferenceProperty(model.RecordModel)
actor = db.ReferenceProperty(model.Profile)
account = db.ReferenceProperty(model.Account)
... and I create an entity like so:
notify = model2.Notification(account=account)
notify.alert = message
notify.type = "reminder"
notify.actor = actor
notify.record = record
notify.put()
This call raises an error *'Notification' object has no attribute '_key'*
nquery = db.Query(model2.Notification).filter('account =', self.session.account).order('-created')
for n in nquery:
try:
_dict = {}
_dict['serverID'] = str(n.key()) #- raises error!
try:
nquery = Notification.all().filter('account =', self.session.account).order('-created')
I think I've figured it out! The "entity" property in my Notification class is causing some sort of naming conflict in python appengine. Changing the name removes the "error object has no attribute '_key'" error. Go figure!

ndb query a model based upon KeyProperty instance

I have a simple ndb model as follows:
class TaskList(ndb.Model):
title = ndb.StringProperty()
description = ndb.TextProperty()
priority = ndb.IntegerProperty()
class UserProfile(ndb.Model):
user = ndb.UserProperty()
tasks = ndb.KeyProperty(TaskList)
As known, a TaskList object will have an Entity Kind Entity Key and an ID.
Given an ID say 7.
I can very well get the object with ID 7 as follows:
task = ndb.Key(TaskList, 7).get()
But how do i get a user who has the task ID 7?
I tried:
tsk = ndb.Key(TaskList, 7).get()
user = UserProfile.query(UserProfile.tasks == tsk.key)
It works, but is there a better method?
You're nearly there - but there's no need to fetch the task, just to use its key property again:
task_key = ndb.Key(TaskList, 7)
user = UserProfile.query(UserProfile.tasks == task_key)
or equivalently:
user = UserProfile.query(UserProfile.tasks == ndb.Key(TaskList, 7))

google datastore many to one references

So i have two model classes:
class Dog(db.model):
dogName = StringProperty()
dogBreed = StringProperty()
class Cat(db.model):
catName = StringProperty()
catBreed = StringProperty()
and then i have a third model class to hold all the pictures
class Images(db.model):
imageReference = ReferenceProperty(*Animal*, collection_name = 'allImages')
imageURL = StringProperty()
Animal is either a Dog or a Cat. Obviously this does not compile.
Now my question is: Is there a way I can put Cat pictures in with Dog pictures? Or do I need to create more models like this:
class DogImages(db.model):
imageReference = ReferenceProperty(Dog, collection_name = 'allImages')
imageURL = StringProperty()
class CatImages(db.model):
imageReference = ReferenceProperty(Cat, collection_name = 'allImages')
imageURL = StringProperty()
You could use PolyModel:
class Animal(polymodel.PolyModel):
name = db.StringProperty()
breed = db.StringProperty()
class Dog(Animal):
pass
class Cat(Animal):
pass
Now you can have a ReferenceProperty that references Animals, and either Dogs or Cats will be permitted.
However, you don't have any properties that are specific to each type of animal - why not just have a regular Animal model, add a property indicating what species it is, and skip the separate models entirely?

Resources