I have these models:
class Article(TimestampedModel):
title = models.CharField(max_length=255)
slug = models.SlugField(db_index=True, max_length=255, unique=True, null=True, blank=True)
introduction = models.TextField(null=True, blank=True)
content = HTMLField('Content')
image = models.ImageField(null=True, blank=True, upload_to='articles')
parent = models.ForeignKey(
'core.Article', on_delete=models.CASCADE, related_name='sectionparent', null=True, blank=True
)
authors = models.ManyToManyField(People, blank=True)
active = models.BooleanField(default=True)
SECTIONS = (
('about', 'About'),
('newsevents', 'News and Events'),
)
section = models.CharField(max_length=20, choices=SECTIONS, default='about')
site = models.ForeignKey(Site, on_delete=models.CASCADE)
objects = models.Manager()
on_site = CurrentSiteManager()
class Event(models.Model):
article = models.OneToOneField(
Article,
on_delete=models.CASCADE,
related_name='event',
),
EVENT_TYPE = (
('match', 'Match'),
('other', 'Other'),
)
start = models.DateTimeField(null=True, blank=True);
end = models.DateTimeField(null=True, blank=True);
type = models.CharField(max_length=20, choices=EVENT_TYPE)
location = models.CharField(max_length=255, null=True, blank=True)
url = models.CharField(max_length=255, null=True, blank=True)
However, when I look at the generated events table in my database, there is no foreign key (I would have expected on). Furthermore, I have a record in Article:
article = Article.objects.find(1)
And then when I try to access the event:
event = article.event
I will get this error:
'Article' object has no attribute 'event'
Related
I'm trying to list the values of FacilityAddressSerializer within the FacilitySearchSerializer. This is what i tried. I get all the values of the FacilitySearchSerializer but the values of the FacilityAddressSerializer are showing as Null:
serializers.py
class FacilityAddressSerializer(serializers.ModelSerializer):
class Meta:
model = FacilityAddress
fields = (
"id",
"PrimaryAddress",
"SecondaryAddress",
"City",
"RegionOrState",
"PostalCode",
"Geolocation",
"AddressInfo"
)
class FacilitySearchSerializer(serializers.ModelSerializer):
AddressInfo = FacilityAddressSerializer(source="fa")
class Meta:
model = Facility
fields = (
"id",
"Name",
"AddressInfo",
"ListingVerified",
"mainimage",
"AdministratorCell",
"Capacity",
"PriceRangeMin",
"PriceRangeMax",
)
read_only_fields = ("id", "Name", "ListingVerified", "mainimage", "AdministratorCell", "Capacity", "FeaturedVideo", "PriceRangeMin", "PriceRangeMax")
models.py
class Facility(models.Model):
Name = models.CharField(max_length=150, null=True, blank=False)
mainimage = models.ImageField(null=True, blank=True)
Capacity = models.IntegerField(null=True, blank=True)
TelephoneNumber = models.CharField(max_length=30, null=True, blank=True)
AdministratorCell = PhoneNumberField(null=True, blank=True)
PriceRangeMin = models.IntegerField(null=True, blank=True)
PriceRangeMax = models.IntegerField(null=True, blank=True)
class FacilityAddress(models.Model):
PrimaryAddress = models.CharField(max_length=150, null=True, blank=True)
SecondaryAddress = models.CharField(max_length=150, null=True, blank=True)
City = models.CharField(max_length=150, null=True, blank=True)
RegionOrState = models.CharField(max_length=50, null=True, blank=True)
PostalCode = models.CharField(max_length=30, null=True, blank=True)
Geolocation = models.CharField(max_length=30, null=True, blank=True)
AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa')
It works after i added (many=True) next to the source=fa. I thought i didn't need that since i'm using foreign key fields and not manytomany fields but i guess i was wrong.
I can't open my Review table, here's the models of code:
This is the `Project` model:
class Project(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
demo_link = models.CharField(max_length=2000, null=True, blank=True)
source_link = models.CharField(max_length=2000, null=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True)
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,
primary_key=True, editable=False)
def __str__(self):
return self.title
And this is the Review model:
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote'),
)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
value = models.CharField(max_length=200, choices=VOTE_TYPE)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False)
def __str__(self):
return self.title
but I can't open my Review table on admin panel (OperationalError at /admin/projects/review/)
Here's the error details:
I make migrations and do migrate:
I have two models in django with definitions below.
CreativeStatus model :
class RtbdCreativeStatus(models.Model):
creative_id = models.CharField(max_length=500, primary_key=True)
advertiser_id = models.CharField(max_length=100, primary_key=True)
exposure_level = models.CharField(max_length=125)
modified_on = models.DateTimeField()
modified_by = models.CharField(max_length=100)
class RtbdCreative(models.Model):
id = models.AutoField(primary_key=True)
advertiser_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
creative_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
country_id = models.IntegerField()
adm = models.CharField(max_length=255, null=True, blank=True)
sample_url = models.CharField(max_length=500)
landing_page = models.CharField(max_length=500, null=True, blank=True)
html = models.CharField(max_length=500)
creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
advertiser_domains = models.CharField(max_length=500)
description = models.CharField(max_length=500, null=True, blank=True)
created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
creative_type = models.CharField(max_length=50, null=True, blank=True)
demand_source_type_id = models.IntegerField()
revalidate = models.BooleanField(default=False)
(creative_id, advertiser_id ) combination is unique in my CreativeStatus table . I want that combination to be my foreign key for Creative table. I tried adding it but i get this error .
1)How do i achieve this join with two key combination as my foreign key .
2)What should be my query to fetch all the creatives with their status from CreativeStatus table .
UPDATE 1
on reading the answers below , i updated my model as mentioned below :
class RtbdCreative(models.Model):
id = models.AutoField(primary_key=True)
advertiser_id = models.ForeignKey(RtbdCreativeStatus, to_field='advertiser_id', related_name='advertiser', db_column='advertiser_id', on_delete=models.CASCADE)
creative_id = models.ForeignKey(RtbdCreativeStatus, to_field='creative_id', related_name='creative', db_column='creative_id', on_delete=models.CASCADE)
country_id = models.IntegerField()
adm = models.CharField(max_length=255, null=True, blank=True)
sample_url = models.CharField(max_length=500)
landing_page = models.CharField(max_length=500, null=True, blank=True)
html = models.CharField(max_length=500)
creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
advertiser_domains = models.CharField(max_length=500)
description = models.CharField(max_length=500, null=True, blank=True)
created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
creative_type = models.CharField(max_length=50, null=True, blank=True)
demand_source_type_id = models.IntegerField()
revalidate = models.BooleanField(default=False)
Now i am getting this error . I have combination of advertiser_id , craetive_id as unique . But django expects both to be unique. What can i do to make it work ?
As mentioned in ERRROS, you need to add related_name as argument, when you want to add more than one foreign key for same Model.
class Creative(models.Model):
id = models.AutoField(primary_key=True)
advertiser_id = models.ForeignKey(RtbdCreativeStatus,
related_name="Advertiser", on_delete=models.CASCADE)
creative_id = models.ForeignKey(RtbdCreativeStatus,
related_name="Creative",
on_delete=models.CASCADE)
country_id = models.IntegerField()
adm = models.CharField(max_length=255, null=True, blank=True)
sample_url = models.CharField(max_length=500)
landing_page = models.CharField(max_length=500, null=True, blank=True)
html = models.CharField(max_length=500)
creative_attributes = models.CommaSeparatedIntegerField(
max_length=150, null=True, blank=True)
advertiser_domains = models.CharField(max_length=500)
description = models.CharField(max_length=500, null=True, blank=True)
created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
creative_type = models.CharField(max_length=50, null=True, blank=True)
demand_source_type_id = models.IntegerField()
revalidate = models.BooleanField(default=False)
I just saw a parameter as to_fields for models.ForeignObject, superclass of models.ForeignKey. It might be used in this case for defining foreign key for composite primary key or unique keys.
advertiser_creative_id = models.ForeignObject(RtbdCreativeStatus, to_fields=['advertiser_id', 'creative_id'], related_name='abc', on_delete=models.CASCADE)
There is a from_fields parameter as well. It can be used to map the fields with to_fields.
Refer https://docs.djangoproject.com/en/2.2/_modules/django/db/models/fields/related/
When you add multiple ForeignKeys towards same table, you should override the related_name option of your fields, so that the fields could be distinguished easily.
You could implement a custom validation for checking uniqueness of the creative_id and advertiser_id,
class Creative(models.Model):
advertiser_id = models.ForeignKey(CreativeStatus,
related_name="advertisers")
creative_id = models.ForeignKey(CreativeStatus,
related_name="creatives")
def clean(self):
data = self.cleaned_data
if not data['advertiser_id'] == data['creative_id']:
raise ValidationError("Unique Constraint failed {}, {}".format(self.advertiser_id, self.creative_id))
return data
You could query your creatives from CreativeStatus using the related name.
creative_status_obj = CreativeStatus.objects.get(pk=some_pk)#or any query.
#All creatives of the given object can be queried using reverse relation.
creatives = creative_status_obj.creatives.all()
Data import using django-import-export is failing for m2m relationships.
The transaction doesn't generate any errors, however when trying to update an object's m2m relationship none of the updated values for m2m are being updated.
models.py
class Category(MPTTModel):
name = models.CharField(max_length=155, verbose_name=_('Category'))
code = models.CharField(max_length=255, verbose_name=_('Category Code'), help_text='primary key value for category', db_index=True)
categorytype = models.ForeignKey(ProductType, related_name='categories_for', verbose_name=_('Product type'), blank=True, null=True)
meta_description = models.TextField(verbose_name=_('Meta Description'))
meta_keywords = models.TextField(verbose_name=_('Meta Keywords'))
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
slug = models.SlugField(blank=True, verbose_name=_('URL alias'))
order = models.PositiveIntegerField()
class Product(models.Model):
reference = models.CharField(max_length=50, verbose_name=_('Reference'), db_index=True)
name = models.CharField(max_length=255, verbose_name=_('Product Name'))
description = models.TextField(blank=True, verbose_name=_('Product Description'))
specs = models.TextField(blank=True, verbose_name=_('Product Specifications'))
color_code = models.ForeignKey(ColorCode, verbose_name=_('Color Code'), related_name='colorcode_for')
color_web = models.CharField(max_length=7, verbose_name=_('Web Color'), db_index=True)
size = models.CharField(max_length=11, verbose_name=_('Product Size'))
price = models.IntegerField(verbose_name=_('Product Price'))
price_promo = models.IntegerField(blank=True, null=True, verbose_name=_('Product Promo Price'))
upc = models.CharField(max_length=155, verbose_name=_('UPC'))
stock = models.IntegerField(verbose_name=_('Product Stock'))
categories = models.ManyToManyField(Category, verbose_name=_('Estilo'), related_name='products')
in_stores = models.BooleanField(default=True, verbose_name=_('Product Availability'), db_index=True)
try_out = models.BooleanField(default=False, verbose_name=_('Try out Product'))
pub_date = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
slug = models.SlugField(default='', blank=True, verbose_name=_('URL alias'))
blog = models.URLField(blank=True, verbose_name=_('Blog mention link'))
parent_product = models.BooleanField(default=False, verbose_name=_('Main Product'), db_index=True)
main_product = models.ForeignKey('Product', blank=True, null=True, related_name='child_product')
active = models.BooleanField(default=True, verbose_name=_('Active'), db_index=True)
trends = models.ManyToManyField(Trends, verbose_name=_('Trends'), blank=True, related_name="trends")
photoshoot_id = models.CharField(max_length=255, verbose_name=_('Photoshoot ID'), blank=True)
new_arrival = models.BooleanField(default=False, db_index=True)
resources.py
class ProductResource(resources.ModelResource):
categories = fields.Field(widget=widgets.ManyToManyWidget(Category, separator="/"))
def export(self, queryset=None):
queryset = Product.objects.all()
headers = self.get_export_headers()
data = tablib.Dataset(headers=headers)
for obj in queryset.iterator():
data.append(self.export_resource(obj))
return data
class Meta:
model = Product
fields = ('categories', 'reference', 'name_es', 'name_en', 'description_es', 'description_en', 'specs_es', 'specs_en', 'color_code', 'color_web', 'size', 'price_es', 'price_en', 'price_promo_es', 'price_promo_en', 'upc', 'stock', 'in_stores', 'try_out', 'blog', 'active', 'photoshoot_id')
import_id_fields = ['upc']
skip_unchanged = True
Issue was fixed removing the skip_unchanged meta option, the skip_rowmethod in the ModelResource class is not reading the new value assigned in the .CSV
Hi I am recreating a website in django and this happens...
Django throw this error,
ValueError: save() prohibited to prevent data loss due to unsaved related object 'fk_deal'.
even though I have saved the foreign key related object. This is the view part.
if request.method == "POST":
deal = DEAL()
name = request.POST.get('name')
revenue_2013 = request.POST.get('revenue_2013')
if project_name:
print project_name
deal.name = project_name
deal.save()
print deal.id # prints None
# financials 2013
if revenue_2013:
fin = DEALFINANCIALINFORMATION.objects.create(
financial_category_amount=revenue_2013,
financial_year='2013',
fk_deal = deal,
financial_category_id=1,
)
These are the models....
class DEAL(models.Model):
id = models.BigIntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
company_name = models.CharField(max_length=33L, db_column=u'COMPANY_NAME', blank=True)
investmentrequired = models.FloatField(null=True, blank=True)
is_deleted = MySQLBooleanField(db_column=u'IS_DELETED', blank=True, default=None)
name = models.CharField(max_length=33L, db_column=u'NAME', blank=True)
photo = models.CharField(max_length=66L, db_column=u'PHOTO', blank=True)
status = models.CharField(max_length=85L, db_column=u'STATUS', blank=True)
timestamp = models.DateTimeField(null=True, db_column=u'TIMESTAMP', blank=True)
teaser = models.TextField(db_column=u'TEASER', blank=True)
currency_id = models.BigIntegerField(null=True, db_column=u'CURRENCY_ID', blank=True)
description = models.TextField(db_column=u'DESCRIPTION', blank=True)
country = models.ForeignKey('COUNTRIES', null=True, db_column=u'COUNTRY_ID', blank=True)
sector = models.ForeignKey('SECTORS', null=True, db_column=u'SECTOR_ID', blank=True)
type = models.ForeignKey('TYPES', null=True, db_column=u'TYPE_ID', blank=True)
username = models.CharField(max_length=85L, db_column=u'USERNAME', blank=True)
user = models.ForeignKey('USER', null=True, db_column=u'USER_ID', blank=True)
hitcounter = models.BigIntegerField(null=True, db_column=u'HITCOUNTER', blank=True)
approx_usd = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'approxUSD', blank=True)
userdeal_id = models.BigIntegerField(null=True, db_column=u'USERDEAL_ID', blank=True)
is_featuredeal = MySQLBooleanField(db_column=u'IS_FEATUREDEAL', blank=True, default=None)
basic_company_email = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_EMAIL', blank=True)
basic_company_name = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_NAME', blank=True)
basic_company_phone = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_PHONE', blank=True)
basic_company_website = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_WEBSITE', blank=True)
basic_elevator_pitch = models.TextField(db_column=u'BASIC_ELEVATOR_PITCH', blank=True)
basic_premoney_evaluation = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'BASIC_PREMONEY_EVALUATION', blank=True)
basic_question_1 = models.TextField(db_column=u'BASIC_QUESTION_1', blank=True)
basic_question_2 = models.TextField(db_column=u'BASIC_QUESTION_2', blank=True)
basic_question_3 = models.TextField(db_column=u'BASIC_QUESTION_3', blank=True)
basic_summary = models.TextField(db_column=u'BASIC_SUMMARY', blank=True)
basic_total_offering_amount = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'BASIC_TOTAL_OFFERING_AMOUNT', blank=True)
is_company = MySQLBooleanField(db_column=u'IS_COMPANY', blank=True, default=None)
is_posted = MySQLBooleanField(db_column=u'IS_POSTED', blank=True, default=None)
is_visible = MySQLBooleanField(db_column=u'IS_VISIBLE', blank=True, default=None)
other_company_milestones = models.TextField(db_column=u'OTHER_COMPANY_MILESTONES', blank=True)
projectname = models.CharField(max_length=33L, db_column=u'PROJECTNAME', blank=True)
basicdealstage = models.ForeignKey('DEALSTAGES', null=True, db_column=u'BASICDEALSTAGE_ID', blank=True)
basic_security_type = models.ForeignKey('SECURITYTYPES', null=True, db_column=u'BasicSecurityType_ID', blank=True)
is_public = MySQLBooleanField(db_column=u'IS_PUBLIC', blank=True, default=None)
profile_completed = models.BigIntegerField(null=True, db_column=u'PROFILE_COMPLETED', blank=True)
is_closed = MySQLBooleanField(db_column=u'IS_CLOSED', blank=True, default=None)
first_step_completed = models.BigIntegerField(null=True, db_column=u'FIRST_STEP_COMPLETED', blank=True, default=0L)
second_step_completed = models.BigIntegerField(null=True, db_column=u'SECOND_STEP_COMPLETED', blank=True)
third_step_completed = models.BigIntegerField(null=True, db_column=u'THIRD_STEP_COMPLETED', blank=True)
class Meta:
db_table = u'DEAL'
def __unicode__(self):
if self.name:
return self.name
else:
return "No name"
class DEALFINANCIALINFORMATION(models.Model):
id = models.BigIntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
financial_category_amount = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'FINANCIAL_CATEGORY_AMOUNT', blank=True)
financial_year = models.CharField(max_length=33L, db_column=u'FINANCIAL_YEAR', blank=True)
de_al_id = models.BigIntegerField(null=True, db_column=u'DEAl_ID', blank=True)
financial_category_id = models.BigIntegerField(null=True, db_column=u'FINANCIAL_CATEGORY_ID', blank=True)
fk_deal = models.ForeignKey('DEAL', null=True, blank=True)
class Meta:
db_table = u'DEAL_FINANCIAL_INFORMATION'
The database was created from an existing MySQL database....
I send the data to the view using jquery POST....
I can't seem to find out what the problem is. Also even after saving the model if I print the id field it returns None instead....
Can somebody help me?