Why should I set default value of foreign key, django - python

For example, we have this code:
class Foo(models.Model):
a = models.CharField(max_length=10)
class Bar(models.Model):
b = models.CharField(max_length=10)
a = models.ForeignKey(Foo)
And when I run makemigrations, i see that I need set default of a(Bar)
Can anyone explain me, why should I do it?
Thanks!

It seems that you already have some data in your database (or you have made a migration before adding the ForeignKey field). In order for the migration to work you will need to "tell" Django what data should be in the a column of the Bar table for rows that already exist.
Either delete your whole database/earlier migrations, or provide a default value of your choice:
a = models.ForeignKey(Foo, default=None) # or any other default value

Related

How to use variables in django models.py, (DEFAULT properties of fields)

I would like that, when clicking on one of the companies below, a variable is stored (until the browser is closed) with the company's code.
And, I need this variable to populate the 'CompanyCode' fields as default value.
FOR EXAMPLE:
class Employee(models.Model):
class Meta:
db_table = 'employee'
CompanyCode= models.IntegerField(
null=False,
blank=None,
default = 'VARIABLE',
db_column='CompanyCode'
)
After being stored in the database, I need to make a query to show all tuples where CompanyCode is equal to a certain value.
Could someone tell me a python, django component that I could use to separate the data for each company? I thought of using JavaScript Local Storage at first.

How do I add a polymorphic class in Django?

I am trying to make an application for a restaurant in django; I have to create a menu for different types of items, and all of those different types of items have to essentially be a product, so that I can add that product to a user's corresponding cart. Here are my menu items:
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
price = models.DecimalField(decimal_places=2, max_digits=10)
class Pizza(Product):
pizzatype = models.CharField(max_length=15)
extras = models.TextField(max_length=50)
size = models.CharField(max_length=10)
class Subs(Product):
name = models.TextField(max_length=64)
size = models.CharField(max_length=10)
class DinnerPlatters(Product):
name = models.TextField(max_length=64)
size = models.CharField(max_length=10)
class Pasta(Product):
name = models.TextField(max_length=64)
class Salads(Product):
name = models.TextField(max_length=64)
As can be seen, I tried deriving the models for different types of menu items from a single model Product, but while running makemigrations, I get the following message on the terminal:
You are trying to add a non-nullable field 'product_ptr' to dinnerplatters 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
I tried googling the solution to my problem, but couldn't find an approriate solution.
I am new to Django and this is my first application, so any help or any other method on how to approach my problem would be kindly appreciated.
As your models inherit from the Product's model, you are using Multi-table inheritance. Now that Multi-table inheritance automatically creates OneToOneField as classname_ptr between inheritance model and base model, your models which is inherit from product's model has product_ptr field. As your model has product_ptr field, you should add default value for existing rows which is save before by you.
https://docs.djangoproject.com/en/3.0/topics/db/models/#multi-table-inheritance

Can I create model in Django without automatic ID?

I need a table without a primary key (in Django it was created automatically). So my question is: Can I create a model without an ID/primary key?
I'm using Django 1.7.
You can create a model without an auto-incrementing key, but you cannot create one without a primary key.
From the Django Documentation:
If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.
Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).
No, you can't. Excerpt from the documentation:
Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).
I've found the solution.
Since django need Primary Key (either it's composite or single-field ID) so, I've tried to set primary_key=True in every fields in its composite-key combination, and add those fields in Meta and groups in unique_together
class ReportPvUv(models.Model):
report_id = models.ForeignKey(Reports, primary_key=True)
rdate = models.DateField(primary_key=True)
fdate = models.DateTimeField(primary_key=True)
ga_pv = models.BigIntegerField()
ga_uv = models.BigIntegerField()
ur_pv = models.BigIntegerField()
ur_uv = models.BigIntegerField()
da_pv = models.BigIntegerField()
da_uv = models.BigIntegerField()
class Meta:
db_table = 'report_pv_uv'
unique_together = ('report_id', 'rdate', 'fdate')
and when I run makemigrations, there are no ID field in it's migrations script :D
thanks everybody

how to update model in django by adding new primary key field?

How to replace default primary key in Django model with custom primary key field?
I have a model with no primary key defined at first since django automatically adds an id field by default as primary field.
#models.py
from django.db import models
class Event(models.Model):
title = models.CharField(max_length=50, unique=True)
description = models.CharField(max_length=150)
I added some objects into it from django shell.
>>e = Event('meeting', 'Contents about meeting')
>>e.save()
>>e = Event('party', 'Contents about party')
>>e.save()
Then I require to add custom character field as primary into this model.
class Event(models.Model):
event-id = models.CharField(max_length=50, primary_key=True)
...
Running makemigrations:
$ python manage.py makemigrations
You are trying to add a non-nullable field 'event-id' to event 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: 1
Please enter the default value now, as valid Python
The datetime and `django.utils.timezone modules` are available, so you can do e.g. timezone.now()
>>> 'meetings'
Migrations for 'blog':
0002_auto_20141201_0301.py:
- Remove field id from event
- Add field event-id to event
But while running migrate it threw an error:
.virtualenvs/env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 485, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: blog_event__new.event-id
In my experience (using Django 1.8.* here), I've seen similar situations when trying to update the PK field for models that already exist, have a Foreign Key relationship to another model, and have associated data in the back-end table.
You didn't specify if this model is being used in a FK relation, but it seems this is the case.
In this case, the error message you're getting is because the data that already exists needs to be made consistent with the changes you're requesting --i.e. a new field will be the PK. This implies that the current PK must be dropped for django to 'replace' them. (Django only supports a single PK field per model, as per docs[1].)
Providing a default value that matches currently existing data in the related table should work.
For example:
class Organization(models.Model):
# assume former PK field no longer here; name is the new PK
name = models.CharField(primary_key=True)
class Product(models.Model):
name = models.CharField(primary_key=True)
organization = models.ForeignKey(Organization)
If you're updating the Organization model and products already exist, then existing product rows must be updated to refer to a valid Organization PK value. During the migration, you'd want to choose one of the existing Organization PKs (e.g. 'R&D') to update the existing products.
[1] https://docs.djangoproject.com/en/1.8/topics/db/models/#automatic-primary-key-fields
Django has already established an auto incrementing integer id as primary key in your backend as and when u made the previous model.
When u were trying to run the new model , An attempt was made to recreate a new primary key column that failed.
Another reason is,When u made the field,Django was expecting a unique value be explicitly defined for each new row which it couldn't found,hence the reason.
As told in previous answer you can re-create the migration and then try doing it again.It should work.. cheers :-)
The problem is that you made the field unique, then attempted to use the same value for all the rows in the table. I'm not sure if there's a way to programmatically provide the key, but you could do the following:
Delete the migration
Remove the primary_key attribute from the field
Make a new migration
Apply it
Fill in the value for all your rows
Add the primary_key attribute to the field
Make a new migration
Apply it
It's bruteforce-ish, but should work well enough.
Best of luck!

Django create_or_update(), unique_together, unique, and primary

I'm still trying to fully understand Django models, let's say I have the following model:
class Manufacturer(models.Model):
name = models.CharField(amx_length=255, unique=True)
class Car(models.Model):
name = models.CharField(max_length=255)
color = models.CharField(max_length=255)
manufacturer = models.ForeignKey(Manufacturer)
unique_together = ('manufacturer', 'name')
And I run the following commands:
honda = Manufacturer.objects.get(name='Honda') #Let's assume this object already exists
car = Car.objects.get_or_create(name='Honda Accord', color='Red', manufacturer=honda)
car = Car.objects.get_or_create(name='Honda Accord', color='Green', manufacturer=honda)
Will Django simply update the existing car to change the color from Red to Green? Or will issues arise because I don't have a primary_key set?
Also, does it matter if I use primary_key or unique or are they the same? I'm using a mySQL backend if it matters.
Django automatically sets a primary key field called id unless you specify one yourself. So your Car model will already have an id field. It's on the base model class that your model inherits.
In your example, you haven't specified the defaults argument of the get_or_create() method, so Django will only attempt to retrieve an object with the values you've passed in via a get call: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#django.db.models.query.QuerySet.get_or_create
unique constraints can be specified on a field regardless if it's an AutoField or not. See: https://docs.djangoproject.com/en/1.7/ref/models/fields/#unique for more specific information.

Categories