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.
Related
THe error upon clicking the POST button on Djangorest Form
The serializer:
class CreatePolicyBenefitsSerializer(serializers.ModelSerializer):
class Meta:
model = Policy
fields = ('company','name','benefits','price')
The views:
class CreatePolicyBenefits(CreateAPIView):
queryset = Policy.objects.all()
serializer_class = CreatePolicyBenefitsSerializer
The Policy Model
``
class Policy(TimeStampedModel):
POLICY_CHOICES = (
('life', 'Life'),
('health', 'Health'),
('home', 'Home'),
('car', 'Car'),
('vul', 'VUL'),
)
PREMIUM_INTERVALS = (
('one_time', 'One Time'),
('annual', 'Annual'),
('semi_annual', 'Semi Annual'),
('quarterly', 'Quarterly'),
('monthly', 'Monthly')
)
company = models.ForeignKey(
'Company', related_name='Policies', on_delete=models.CASCADE,
null=True, blank=True)
name = models.CharField(max_length=255, blank=True, null=True, default="")
description = models.TextField(blank=True, null=True, default="")
benefits = models.JSONField(null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
category = models.CharField(
max_length=64, blank=True, null=True, choices=POLICY_CHOICES, default="")
premium_details = models.CharField(max_length=255, blank=True, null=True)
policy_details = models.CharField(max_length=255, blank=True, null=True)
available_premium_interval = models.CharField(
max_length=64, blank=True, null=True, choices=PREMIUM_INTERVALS)
icon_name = models.CharField(max_length=32, blank=True, null=True)
icon_file = models.FileField(
upload_to=upload_policy_icon, blank=True, null=True)
primary_color = models.CharField(max_length=32, blank=True, null=True)
# file=models.FilePathField(path=os.path.join(settings.MEDIA_ROOT, 'media'))
adminupload=models.FileField(upload_to=pdf_path,max_length=None)
pdfname=models.CharField(max_length=255, blank=True, null=True)
class Meta:
app_label = samplename
def __str__(self):
return '[%s] %s-%s' % (self.id, self.company, self.name)
Here the form
Is it possible when I hit POST button, the data can be displayed on the form? Thanks
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'
I'm using django-filter and I would like to ask you if it could filter one to many reliontionship because I did not found any doc or example even on StackOverflow., here are the model, the filter and the view
class Aliens(models.Model):
class Meta:
db_table = 'aliens'
verbose_name = ('Introduction Event')
verbose_name_plural = ('Introuction Events')
ordering = ['alien']
alien = models.OneToOneField(Taxonomy, verbose_name=u"Non-indigenous Species",
on_delete=models.CASCADE, null=True, blank=True)
#SpeciesName = models.CharField(max_length=100, verbose_name=u"Species Name", blank=True, null=True)
group = models.OneToOneField(Ecofunctional, verbose_name=u"Ecofunctional Group", on_delete=models.CASCADE,
blank=True, null=True, default='')
firstsight = models.IntegerField(('First Mediterranean Sighting'), choices=YEAR_CHOICES, blank=True, null=True)
med_citation = models.ForeignKey(biblio, verbose_name=u"Mediterranean first citation", on_delete=models.CASCADE,
null=True, blank=True)
origin = models.OneToOneField(Origin, on_delete=models.CASCADE, blank=True, null=True, default='',
verbose_name=u"Origin")
status = models.OneToOneField(SuccessType, on_delete=models.CASCADE, blank=True, null=True, default='',
verbose_name=u"Establishement")
created_by = CurrentUserField()
created_at = models.DateField('date of inclusion', blank=True, null=True, default=datetime.datetime.now())
photo = models.ImageField(upload_to='photos', blank=True, null=True)
vector = models.ManyToManyField(vectors, verbose_name=u"Vectors/Pathways")
updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now())
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated',
default=CurrentUserField(), null=True)
notes = models.TextField(verbose_name='Notes', blank=True, null=True)
db_status = StateField(verbose_name='Species Status in the Db', blank=True, null=True)
def __str__(self): # __unicode__ on Python 2
return self.alien.SpeciesName
class Distributions(models.Model):
class Meta:
db_table = 'distributions'
verbose_name = ('verified occurence')
verbose_name_plural = ('verified occurences')
alien = models.ForeignKey(Aliens, verbose_name=u"Non-Indeginous Species", related_name='distributions',
on_delete=models.CASCADE, null=True, blank=True)
country = models.OneToOneField(Country, on_delete=models.CASCADE, verbose_name='Country', blank=True, null=True)
seas = models.OneToOneField(regionalseas, on_delete=models.CASCADE, verbose_name='Regional Sea', blank=True,
null=True)
MSFD = models.OneToOneField(MSFD, on_delete=models.CASCADE, verbose_name='MSFD/EcAp Sub-region', blank=True,
null=True)
area1stSighting = models.DateField('First Areas Sighting', blank=True, null=True, default=datetime.datetime.now())
AreaSuccessType = models.OneToOneField(SuccessType, on_delete=models.CASCADE,
verbose_name='Area Establishement/Success', blank=True, null=True)
Area_citation = models.ForeignKey(biblio, verbose_name=u"Area first citation", on_delete=models.CASCADE, null=True,
blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_created',
default='')
created_at = models.DateField('date of Edition', blank=True, null=True, default=datetime.datetime.now())
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated',
default='')
updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now())
notes = models.TextField(verbose_name='Notes', blank=True, null=True)
dverification = StateField(verbose_name='Validated ')
def __str__(self): # __unicode__ on Python 2
return self.alien.SpeciesName
class AliensFilter(django_filters.FilterSet):
country = filters.ModelChoiceFilter(label='Country', queryset=Country.objects.all())
msfd = filters.ModelChoiceFilter(label='MSF/EcAp Subregions', queryset=MSFD.objects.all())
regseas = filters.ModelChoiceFilter(label='Regional Seas', queryset=regionalseas.objects.all())
vector = filters.ModelChoiceFilter(label='Vectors/Pathway', queryset=vectors.objects.all())
Species = filters.ModelChoiceFilter(label='Species Name', queryset=Taxonomy.objects.all())
class Meta:
model = Aliens
fields = (
'Species', 'group', 'origin', 'firstsight', 'status', 'vector', 'country', 'msfd', 'regseas')
def search(request):
Aliens_list = Aliens.objects.all().select_related('origin', 'status', 'group', 'Taxonomy')
aliens_filter = AliensFilter(request.GET, queryset=Aliens_list)
# return render(request, 'mamias/list.html', {'filter': aliens_filter})
return render(request, 'mamias/list2.html', {'filter': aliens_filter})
How could I filter based on country for example?
There is no direct relationship between the Aliean and Country models. You would need to instead filter by country through the distributions relationship.
from django_filters import FilterSet, filters
class AlienFilter(FilterSet):
country = filters.ModelChoiceFilter(
field_name='distributions__country',
queryset=Country.objects.all(),
)
This is my first model
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID = models.CharField(max_length=11, blank=True, null=True)
SiswaNIS = models.CharField(max_length=7, null=True, blank=True, unique=True)
and this is my second model
class Transaksi(models.Model):
tanggal = models.DateField(null=True, blank=True)
keterangan = models.CharField(max_length=100, null=True, blank=True)
nominal = models.IntegerField(null=True, blank=True)
nis = models.CharField(max_length=7, null=True, blank=True)
how to make inner join query from that model without relation from those models where DataPribadiSiswa.Siswanis same with Transaksi.nis.
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