I'm trying a simple model inheritance:
class Product(models.Model):
creation_date = models.DateTimeField(auto_now_add=True)
class Application(Product):
name = models.CharField(max_length=200)
'makemigrations' asks for a default:
You are trying to add a non-nullable field 'product_ptr' to
application without a default; we can't do that (the database needs
something to populate existing rows).
I saw here that I could Product an abstract model with a Meta class, but I can't do that since I'm refereing it specifically in other models as an actual model:
class Comment(models.Model):
product = models.ForeignKey('Product', related_name="comments")
Running 'makemigrations' when the database is removed also leads to the same issue.
Anything I can do?
Django 1.9
You haven't explained what exactly is the change that you have made, it seems that you have changed your Application model to inherit from Product where it previously inherited from models.Model. That causes django to create a 1 to 1 mapping behind the scenes. The addition of the product_ptr which you didn't add to the model yourself enters the picture
ref: https://docs.djangoproject.com/en/1.9/topics/db/models/#multi-table-inheritance
The inheritance relationship introduces links between the child model
and each of its parents (via an automatically-created OneToOneField).
It's a bit tricky to add this field to a table with data during a migration because this field needs to be unique. If you are merely creatig a new model named Application, a value of 1 would be ok.
Related
Good day i seem to be lost in how i want to implement something. so here is how it goes
ive got a carowner model
class carowner(models.Model):
.....
carowner = models.CharField(primary_key=True)
and a cars model
class car(models.Model):
....
carowner_id = models.ForeignKey(carowner)
it has a foreignkey cause each car can only have one carowner
but a carowner can have many cars but i run into a situation where
ive got a modelform
class assigncarownertocar(forms.ModelForm):
car= forms.ModelChoiceField(widget=MultipleSelect())
class Meta:
model=carowner
fields = [# all fields that are needed ]
what i want to happen is when im creating a new carowner asigns him multiple cars in the same form from a queryset i provided when the modelform is initialized.
so everything loads fine in the form. i see the list of cars but once i select one or more i get this
'Select a valid choice. 539421 is not one of the available choices.
what i am asking is should i add the modelmultiplechoicefield to the model that holds the foreign key?
cause right now i have it attached to the carowner model. i dont see documentation stating that this is wrong
Say we're building a Django-based site that clones Medium.com's URL structure, where you have users and articles. We'd probably have this model:
class Article(models.Model):
user = models.ForeignKey(User)
slug = models.CharField()
We want to be able to build URLs that look like /<username>/<slug>/. Since we're going to have billions of articles and zillions of pageviews, we want to put an index on that model:
class Meta:
indexes = [
models.Index(fields=['user__username', 'slug'])
]
But this causes the makemigrations command to fail with the following error:
django.core.exceptions.FieldDoesNotExist: Article has no field named 'user__username'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet.
So, plain vanilla models.Index doesn't support relational lookups like a QuerySet does. How would I add an index like this? Let's assume PostgreSQL, if that's helpful.
It seems that you can't make multi-table index according to this answer.
So if it's not possible in the database, I don't see how can Django offer this feature...
What you can do to make your queries more efficients is an index using user_id and slug.
Django index meta class mainly provide declarative options for indexing table fields,
you can create an index using several field of a model or create different index for every fields of the model. you just don't have to provide user foriegnkey field name attribute which generate automatic user_id index migrations
migrations.AddIndex(
model_name='candidates',
index=models.Index(fields=['user'], name='candidates__user_id_569874_idx'),
),
you can also set the index name in the model meta, and db_tablspace as well if needed.
I've seen two ways of extending the User model in Django.
Method 1:
class User(AuthUser):
new fields...
Method 2:
class MyUser(models.Model):
user = models.OneToOneField(User)
new fields...
What is the difference between them?
The first one is multi table inheritance. (I presume you are actually speacking of django.contrib.auth.models.User here). Your new User model will have all the field that are defined in django's user model. This is managed by django implicitly creating a OneToOneField on your model.
The second, one you are creating the OneToOneField yourself. Now the django.contrib.auth.model.User model's fields do not automatically appear as parts of your own model. YOu can still access them as
myinstance.user.parent_field
Having said all this, for option 1 you should inherit from an abstract base class rather than directly from the User model.
class MyUser(AbstractBaseUser):
...
I have looked for django doc in their official site but i can't find the article about the on_update model function here in Related objects reference except for on_delete.
Here is an example code:
from django.db import models
class Reporter(models.Model):
# ...
pass
class Article(models.Model):
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
Is there any version of on_update?
I have visited this Cascade on update and delete wih django but there is not a clear answer about the on_update
I am using mysql and define the relationship in the ERD and sync it to the db and tried running the python manage.py inspectdb to generate the django-model but it shows only models.DO_NOTHING.
Is there a better way to achieve this, if any?
It's normally adviseable to completely leave the primary key alone when setting up your Django models, as these are used by Django in a number of ways to maintain relationships between objects. Django will set them up and use them automatically.
Instead, create a separate field in your model to keep track of unique data:
class Reporter(models.Model):
emp_id = models.CharField(unique=True)
This way you can obtain the emp_id with reporter_object.emp_id and if you need it, you can still get the pk with reporter_object.id.
You can read about how it works it in the Django 1.9 Documentation
I have these models:
class Company(models.Model):
name=models.CharField(max_length=100)
description=models.TextField()
#some more fields
class Product(models.Model):
name=models.CharField(max_length=100)
company=models.ForeignKey(Company)
#some more fields
class Category(models.Model):
parent=models.ForeignKey('self',null=True,blank=True)
name=models.CharField(max_length=100)
products=models.ManyToManyField(Product,null=True,blank=True)
#some more fields
as U can see each company has a list of product and each product belongs to some categories,I'm going to get the list of categories of each company using company pk,what's the best practice?should I define a database view?how can I do this?
Note:I've not ever used database view in django,I searched about it and that doesn't sound easy to me!
I always try to avoid using database views, stored procedures and in general stuff that 'lives' in the database itself rather than in the application code-base for the simple reason that it is very hard to maintain (and also you say good bye to database agnostic applications).
My advice here is to stick with django orm (which can do a lot) and only if you unable to get decent performances or if you need some advanced feature available through stored procedures/views only then to go for that solution.
Using views in django is quite easy.
Say you have 1 view to query, you create the view on the db then you write the model with fields matching the view' columns (name and type).
UPDATE:
You then need to set the table name as the view name in meta class definition.
After that you need to tell django not to write on that and to not try to create a table for the view model, luckily there is a conf for that:
class ViewModel(models.Model):
... view columns ...
class Meta():
db_table = 'view_name'
managed = False
I've no idea why you think you need a db view here. Generally, you don't use them with Django, since you do all the logic in Python via the ORM.
To get the list of categories for a company, you can just do:
categories = Category.objects.filter(products__company=my_company)
where my_company is the Company instance you're interested in.