Related
I have to serialize spare instance from spare variety many to many field.
Models.py
class SpareVariety(models.Model):
quality = models.ForeignKey(Quality, max_length=255, on_delete=models.CASCADE, null=True, blank=True)
variety_name = models.CharField(max_length=255, null=True, blank=True)
property = models.ForeignKey(SpareProperty, null=True, blank=True, on_delete=models.CASCADE)
purchase_price = models.PositiveIntegerField(help_text="in INR", blank=True, null=True)
retail_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
dealer_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
stock_available = models.PositiveIntegerField(blank=True, null=True,default=True)
spare_costing = models.ForeignKey(SpareCosting, on_delete=models.CASCADE, blank=True, null=True)
spare_discount = models.ForeignKey(Discount, on_delete=models.CASCADE, blank=True, null=True)
is_available = models.BooleanField(default=False)
date_added = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(auto_now_add=True)
class Spare(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
spare_variety = models.ManyToManyField(SpareVariety, related_name='spare_varieties', null=True, blank=True)
name = models.CharField(max_length=255, help_text="Enter the name of spare (Ex:Display, Speakers)")
type = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE)
date_added = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.product.name, self.name)
Serialize the spare model from spare variety serializer
serializers.py
class SpareVarietySerializer(serializers.HyperlinkedModelSerializer):
spare_costing= SpareCostingSerializer(many=False, read_only=False)
spare_discount = DiscountSerializer(many=False, read_only=False)
quality = QualitySerializer(many=False, read_only=False)
property = SparePropertySerializer(many=False, read_only=False)
spare_name = serializers.CharField(read_only=True, source="spare.name")
class Meta:
model = SpareVariety
fields = ['id','quality','variety_name','purchase_price','spare_name','retail_price','property', 'dealer_price', 'stock_available','spare_costing','spare_discount','is_available', 'date_added', 'date_updated',]
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 am designing django models for a E-commerce market place site where user can buy 4 type of products . Like I have 4 type of diff models for them .
For clothes
class Merchandise(models.Model):
adOwner = models.ForeignKey(VendorProfile, on_delete=models.CASCADE)
imagesMerchandise = models.ManyToManyField(merchandiseImages)
productName = models.CharField(max_length=50, null=False, blank=False)
price = models.IntegerField()
availableQuality=models.IntegerField()
color=models.CharField(max_length=20, null=False, blank=False)
size = models.CharField(max_length=50 , null=False , blank=False)
description=models.CharField(max_length=250 , null=False , blank=False)
is_approved = models.BooleanField(default=False)
def __str__(self):
return str(self.productName)
for Rent a Car
class Vehicle(models.Model):
adOwner=models.ForeignKey(VendorProfile, on_delete=models.CASCADE)
carImages=models.ManyToManyField(Image)
make=models.CharField(max_length=50, null=False, blank=False)
modelName=models.CharField(max_length=50, null=False, blank=False)
registrationNumber=models.CharField(max_length=50, null=False, blank=False)
modelYear=models.CharField(max_length=50, null=False, blank=False)
modelColor=models.CharField(max_length=50, null=False, blank=False)
carType=models.CharField(max_length=50, null=False, blank=False)
fuelMileage=models.CharField(max_length=50, null=False, blank=False)
SeatingCapacity=models.CharField(max_length=50, null=False, blank=False)
vehicleCondition=models.CharField(max_length=50, null=False, blank=False)
fuelType=models.CharField(max_length=50, null=False, blank=False)
price=models.CharField(max_length=50, null=False, blank=False)
description=models.CharField(max_length=500, null=True, blank=True)
registerIn=models.CharField(max_length=500, null=True, blank=True)
is_approved = models.BooleanField(default=False)
def __str__(self):
return str(self.modelName)
book a hotel
class Accommodation(models.Model):
adOwner = models.ForeignKey(VendorProfile, on_delete=models.CASCADE)
hotleImages = models.ManyToManyField(HotleImages)
accommodationTitle=models.CharField(max_length=150)
location = models.CharField(max_length=150)
accommodationName = models.CharField(max_length=150)
checkIn = models.TimeField()
checkOut = models.TimeField()
# accessibility = models.CharField(max_length=20, null=False, blank=False)
address = models.CharField(max_length=150)
pets = models.CharField(max_length=150)
child = models.CharField(max_length=150)
is_approved = models.BooleanField(default=False)
Create a Activity
class ActivityOrganizer(models.Model):
adOwner = models.ForeignKey(VendorProfile, on_delete=models.CASCADE)
activityImage = models.ManyToManyField(ActivityImage)
activityName = models.CharField(max_length=50 , null=False, blank=False)
activityId = models.CharField(max_length=20, null=False, blank=False)
ageSuggestion = models.CharField(max_length=20, null=True, blank=True)
duration = models.CharField(max_length=20, null=False, blank=False)
openTime = models.TimeField()
closeTime=models.TimeField()
expiryDate = models.DateField()
availableQty = models.IntegerField()
price = models.IntegerField()
needToBring = models.CharField(max_length=50 , null=True , blank=True)
personsAllowOnOneTicket = models.IntegerField()
location = models.CharField(max_length=50 , null=True , blank=False)
specialNotes = models.CharField(max_length=250 ,null=True , blank=True)
description = models.CharField(max_length=250 , null=True , blank=True)
is_approved = models.BooleanField(default=False)
Now I made a order Table like this
class Orders(models.Model):
order_number = models.AutoField(primary_key=True)
total_amount = models.DecimalField(max_digits=10, decimal_places=2)
ordertime = models.DateTimeField(auto_now_add=True)
user_note=models.CharField(max_length=150 , null=True, blank=True)
address=models.CharField(max_length=150 , null=True, blank=True)
order_status = models.CharField(choices=STATUS , max_length=50)
payment_status=models.BooleanField(default=0)
Now I am confuse how to bind all these 4 categories to my order object. as If its a for single category I can simply create a foreign key with order model. But How can I bind all these (as user can pick 1,2,3,4 number of categories ) so if user select Accommodation , and Vehicle categories products how I can save 2 categories null in foreign key. Any help would be highly appreciated . thanks
If you have small number of products (4 in your case) and for each order only one item of a type can be ordered, then you can simply add those to the Orders model with nullable fields
class Orders(models.Model):
order_number = models.AutoField(primary_key=True)
total_amount = models.DecimalField(max_digits=10, decimal_places=2)
ordertime = models.DateTimeField(auto_now_add=True)
user_note=models.CharField(max_length=150 , null=True, blank=True)
address=models.CharField(max_length=150 , null=True, blank=True)
order_status = models.CharField(choices=STATUS , max_length=50)
payment_status=models.BooleanField(default=0)
merchandise = models.ForeignKey(Merchandise, on_delete=models.CASCADE, null=True, blank=True)
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, null=True, blank=True)
accommodation = models.ForeignKey(Accommodation, on_delete=models.CASCADE, null=True, blank=True)
activity_organizer = models.ForeignKey(ActivityOrganizer, on_delete=models.CASCADE, null=True, blank=True)
To list all the orders of a specific category, exclude all the orders with null in given field.
Orders.objects.exclude(merchandise__isnull=True)
Also if only a single category product is ordered rest 3 fields will be null, if you want to enforce that business logic then you can check for it by creating a signal.
I am currently working on django. I created 4 classes in models.py, one of them is ReactionMeta class. This class has 62 columns, which defined as below:
class Reactionsmeta(models.Model):
id = models.ForeignKey('Reactions', db_column='id', primary_key=True, max_length=255, on_delete=models.CASCADE)
name = models.CharField(max_length=255, blank=True, null=True)
metabolite1 = models.ForeignKey('Metabolites', db_column='metabolite1', blank=True, null=True,
on_delete=models.CASCADE)
stoichiometry1 = models.CharField(max_length=255, blank=True, null=True)
metabolite2 = models.ForeignKey('Metabolites', db_column='metabolite2', blank=True, null=True,
on_delete=models.CASCADE, related_name='+')
stoichiometry2 = models.CharField(max_length=255, blank=True, null=True)
metabolite3 = models.ForeignKey('Metabolites', db_column='metabolite3', blank=True, null=True,
on_delete=models.CASCADE, related_name='+')
stoichiometry3 = models.CharField(max_length=255, blank=True, null=True)
metabolite4 = models.ForeignKey('Metabolites', db_column='metabolite4', blank=True, null=True,
on_delete=models.CASCADE, related_name='+')
#...
Some of the reactions, may have 6 metabolites, however, some of reactions may only have 2 metabolites and stoichiometries, which means there is no value of this reaction in metabolite3,4,5,6...columns and stoichiometry 3,4,5,6...columns.
In that case, how can I only display the Charfield with data while undisplay those Charfield with no value in django-admin?
So I think there is model design issue here. For my case i would have done this as follows
class ReactionMeta(models.Model):
reaction = models.ForeignKey(Reaction, ..)
name = models.CharField(..)
data = models.ForeignKey(Data, ..)
Contructing the Data class to hold the Stoichiometry and Metabolite
class Data(models.Model):
stoichiometry = models.CharField(..)
metabolite = models.ForeignKey(..)
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(),
)