can not insert an embedded document into a model using django - python

I can't create an embedded document into a model using django, i'm using djongo as my database.It keeps telling me that my value must be an instance of Model:<class 'django.db.models.base.Model'> even though I have created all the fields in the model. I really need some help....
my model:
class SMSHistory(models.Model):
ThoiGian = models.DateField(default=datetime.date.today,null=True,blank=True)
SoDienThoai = models.CharField(max_length=100,null=True,blank=True)
SeriNo = models.CharField(max_length=100,null=True,blank=True)
Count = models.IntegerField(default=0,null=True,blank=True)
class WebHistory(models.Model):
ThoiGian = models.DateField(default=datetime.date.today,null=True,blank=True)
DiaChiIP = models.CharField(max_length=100,null=True,blank=True)
SoDienThoai = models.CharField(max_length=100,null=True,blank=True)
SeriNo = models.CharField(max_length=100,null=True,blank=True)
Count = models.IntegerField(default=0,null=True,blank=True)
class AppHistory(models.Model):
ThoiGian = models.DateField(default=datetime.date.today,null=True,blank=True)
DiaChiIP = models.CharField(max_length=100,null=True,blank=True)
SoDienThoai = models.CharField(max_length=100,null=True,blank=True)
SeriNo = models.CharField(max_length=100,null=True,blank=True)
Count = models.IntegerField(default=0,null=True,blank=True)
class CallHistory(models.Model):
ThoiGian = models.DateField(default=datetime.date.today,null=True,blank=True)
SoDienThoai = models.CharField(max_length=100,null=True,blank=True)
SeriNo = models.CharField(max_length=100,null=True,blank=True)
Count = models.IntegerField(default=0,null=True,blank=True)
class History(models.Model):
MaTem = models.CharField(max_length=100,null=True,blank=True)
MaSP = models.CharField(max_length=100,null=True,blank=True)
SMS = models.EmbeddedModelField(
model_container = SMSHistory
)
App = models.EmbeddedModelField(
model_container = AppHistory
)
Web = models.EmbeddedModelField(
model_container = WebHistory
)
Call = models.EmbeddedModelField(
model_container = CallHistory
)
my views
class check(View):
def get(self,request):
return render(request,'website/main.html')
def post(self,request):
matem=request.POST.get('txtCheck')
print(matem)
temp=khotemact.objects.filter(MaTem=matem)
print(temp[0])
tim=History.objects.filter(MaTem=temp[0].MaTem)
if len(tim)==0:
print('khong co')
them=History.objects.create(MaTem=temp[0].MaTem,MaSP='123',
SMS={'ThoiGian':'2010-1-1','SoDienThoai':'12324','SeriNo':'12343','Count':0},
App={'ThoiGian':'2010-1-1','DiaChiIP':'1','SoDienThoai':'12324','SeriNo':'1236','Count':0},
Web={'ThoiGian':'2010-1-1','DiaChiIP':'1','SoDienThoai':'12324','SeriNo':'1236','Count':0},
Call={'ThoiGian':'2010-1-1','SoDienThoai':'1233','SeriNo':'123','Count':0}
)
them.save()
else:
print('co')
# History.objects.filter(MaTem=temp[0].MaTem).update(Web={'Count':Count+1})
return HttpResponse('oke')
i received an error like this
ValueError at /website/check/
Value: {'ThoiGian': '2010-1-1', 'SoDienThoai': '12324', 'SeriNo': '12343', 'Count': 0} must be instance of Model: <class 'django.db.models.base.Model'>
thank you

As error says, you should use model instance, and you are using dict
wrong
SMS={'ThoiGian':'2010-1-1','SoDienThoai':'12324','SeriNo':'12343','Count':0}
right
SMS = SMSHistory.objects.create(ThoiGian='2010-1-1', SoDienThoai='12324',SeriNo='12343', Count=0)

Related

Django import export edit queryset before export

I'm trying to calculate the pending amount via models and export result in the csv. But the csv shows an empty column for amountpending
class FinancePendingResource(resources.ModelResource):
invoiceNumber = Field(attribute='invoiceNumber', column_name='Invoice Number')
student = Field(attribute='student', column_name='Student')
Schedule = Field(attribute='Schedule', column_name='Schedule')
TotalAmount = Field(attribute='TotalAmount', column_name='Total Value(PKR ₨)')
issueDate = Field(attribute='issueDate', column_name='Issue Date')
dueDate = Field(attribute='dueDate', column_name='Due Date')
amountPaid = Field(attribute='amountPaid', column_name='Amount Paid (PKR ₨)')
class Meta:
model = FinancePending
import_id_fields = ('invoiceNumber',)
fields = ('invoiceNumber', 'student', 'amountPaid', 'issueDate', 'dueDate', 'Schedule', 'TotalAmount',
'AmountPending',)
exclude = ('id',)
skip_unchanged = True
report_skipped = True
def before_export(self, queryset, *args, **kwargs):
amount_paid = FinancePending.objects.values_list('amountPaid', flat=True)
amount_paid = list(amount_paid)
total_amount = FinancePending.objects.values_list('TotalAmount', flat=True)
total_amount = list(total_amount)
# total - paid
TotalFee = [float(s.replace(',', '')) for s in total_amount]
AmountPaid = [float(s.replace(',', '')) for s in amount_paid]
def Diff(li1, li2):
return (list(set(li1) - set(li2)))
amount_pending = Diff(TotalFee, AmountPaid)
finance_pending = FinancePending()
i = 1
while i <= len(amount_pending):
FinancePending.objects.filter(invoiceNumber=i).update(AmountPending=str(amount_pending[i]))
i = i + 1
queryset.refresh_from_db()
Assuming that you have the data to compute amountPending already in the dataset, perhaps you don't need to read from the DB: you could calculate the amount by processing the dataset in memory. This could be done in after_export(). Then you can added the computed column to the dataset.
Perhaps tablib's dynamic columns can assist in adding the amountPending column:
import decimal
import tablib
headers = ('invoiceNumber', 'amountPaid', 'totalAmount')
rows = [
('inv100', '100.00', "500.00"),
('inv101', '200.00', "250.00")
]
def amount_pending(row):
return decimal.Decimal(row[2]) - decimal.Decimal(row[1])
data = tablib.Dataset(*rows, headers=headers)
data.append_col(amount_pending, header="amountPending")
print(data)
This will produce the following:
invoiceNumber|amountPaid|totalAmount|amountPending
-------------|----------|-----------|-------------
inv100 |100.00 |500.00 |400.00
inv101 |200.00 |250.00 |50.00

Django not finding command when importing CSV data with Dictreader

I would like to use Python's Dictreader to import a csv file based on my Django model into the database.
My post model is:
class Post(models.Model):
STATUS_CHOICES = (
("draft", "Draft"),
("published", "Published")
);
slug = models.SlugField(max_length=250);
wine_id = models.IntegerField();
country = models.CharField(max_length=100);
description = models.TextField();
designation = models.TextField();
price = models.FloatField();
province = models.CharField(max_length=100);
region_1 = models.CharField(max_length=100);
region_2 = models.CharField(max_length=100);
variety = models.CharField(max_length=100);
winery = models.CharField(max_length=100);
objects = models.Manager();
class Meta:
ordering = ("id",);
def __str__(self):
return self.variety;
def get_absolute_url(self):
return reverse("post_detail", args=[self.id,
self.province,
self.slug]);
My script to read the csv data is:
class Command(BaseCommand):
# Shows this when the user types help:
help = "Loads data from wine_data.csv into our Post model.";
def handle(self, *args, **kwargs):
if Post.objects.exists():
print("Wine data already loaded... exiting...");
print(ALREADY_LOADED_ERROR_MESSAGE);
return;
print("Loading wine data for WCC.");
for row in DictReader(open("wine_data.csv")):
post = Post();
post.wine_id = row["wine_id"];
post.country = row["country"];
post.description = row["description"];
post.designation = row["designation"];
post.price = row["price"];
post.province = row["province"];
post.region_1 = row["region_1"];
post.region_2 = row["region_2"];
post.variety = row["variety"];
post.winery = row["winery"];
post.save();
However, when I use "python manage.py load_wine_data", the cmd says it is an unknown command. What am I doing wrong and how can I solve it?

How to fill through model instances using forms or formsets

I have the following models :
class criterion(models.Model):
quantity = '0'
quality = '1'
ascending = '0'
descending = '1'
three = '3'
five = '5'
seven = '7'
ten = '10'
type_choices = (
(quantity,'Ποσοτικό'),
(quality,'Ποιοτικό'),
)
monotonicity_choices = (
(ascending,'Αύξον'),
(descending,'Φθίνον'),
)
a_choices = (
(three,'Τριβάθμια'),
(five,'Πενταβάθμια'),
(seven,'Εφταβάθμια'),
(ten,'Δεκαβάθμια'),
)
criterion_research = models.ForeignKey('research', on_delete=models.CASCADE,null=True)
criterion_name = models.CharField(max_length = 200,verbose_name='Όνομα Κριτηρίου')
criterion_type = models.CharField(max_length = 15,choices = type_choices , default = quantity,verbose_name='Τύπος')
criterion_monotonicity = models.CharField(max_length = 15,choices = monotonicity_choices , default = ascending,verbose_name='Μονοτονία')
criterion_a = models.CharField(max_length = 30,choices = a_choices , default = five,verbose_name='Κλίμακα',help_text='Επιλέξτε μία από τις 4 κλίμακες που θα μετρηθεί το κριτήριο.')
criterion_worst = models.FloatField(default=' ',verbose_name='Χειρότερη Τιμή',help_text='Επιλέξτε τη χειρότερη τιμή την οποία μπορεί να πάρει το κριτήριο.',blank=True)
criterion_best = models.FloatField(default=' ',verbose_name='Καλύτερη Τιμή',help_text='Επιλέξτε τη καλύτερη τιμή την οποία μπορεί να πάρει το κριτήριο.',blank=True)
def __str__(self):
return self.criterion_name
class alternative(models.Model):
name = models.CharField(max_length = 200,verbose_name='Όνομα Εναλλακτικής')
ranking = models.IntegerField(default='1')
alternative_research = models.ForeignKey('research', on_delete=models.CASCADE)
criteria = models.ManyToManyField('criterion', through='criterionvalue',blank=True)
def __str__(self):
return self.name
class criterionvalue(models.Model):
value = models.IntegerField(default='0')
alt = models.ForeignKey('alternative',on_delete=models.CASCADE)
crit = models.ForeignKey('criterion',on_delete=models.CASCADE)
I have made a view that populates the criterion instances and the alternative instances(except the manytomany field).
I want to query for all the possibles criterion and alternatives and then based on that populate the criterionvaue instances.After I complete these I want then to specify the manytomany relatioship of the criterionvalue instances with the alternatives instances .I thought of making a formset of criterionvalue model then associate them(the forms made by the formset) with the alternatives and criteria using the length of the alternatives and criteria queryset(In order to render the relatioship matrix using forms) .
But I think such an idea is farfetched.
Any ideas on how i could achieve such thing ?

Save function in django/python duplicating entries

I'm writing a football scoring app for a local league using the same schema as the NFL's gameday DB. I created a function that will eventually run on it's own updating each player's scores.
The problem comes when the function to create a new points record is run it duplicates the entry for each player, there's no error shown or anything, everything runs as expected except for the duplicate values.
here are my views.py:
def updatepoints(request):
actual = get_object_or_404(CurrentWeek, status='active')
week = actual.week
season = actual.season
ptsexist = Puntos.objects.filter(week=week, season=season)
if ptsexist:
pts = Player.objects.raw('''SELECT DISTINCT player.player_id,(SELECT (SELECT SUM(play_player.passing_yds))+(SELECT SUM(play_player.passing_tds))+(SELECT SUM(play_player.passing_twoptm))+(SELECT SUM(play_player.passing_int))+(SELECT SUM(play_player.rushing_yds))+(SELECT SUM(play_player.rushing_tds))+(SELECT SUM(play_player.rushing_twoptm))+(SELECT SUM(play_player.fumbles_lost))+(SELECT SUM(play_player.receiving_yds))+(SELECT SUM(play_player.receiving_tds))+(SELECT SUM(play_player.receiving_twoptm))+(SELECT SUM(play_player.receiving_rec))+(SELECT SUM(play_player.kicking_fgm))+(SELECT SUM(play_player.kicking_xpmade))+(SELECT SUM(play_player.fumbles_rec_tds))+(SELECT SUM(play_player.kicking_rec_tds))) AS total,id_puntos FROM player INNER JOIN play_player ON player.player_id = play_player.player_id INNER JOIN game ON play_player.gsis_id = game.gsis_id LEFT JOIN points ON player.player_id = points.player_id AND points.temporada = game.season_year AND "DraftFantasy_puntos".semana = game.week WHERE game.week = %s AND game.season_year = %s AND game.season_type != 'Warmup' AND game.season_type != 'Postseason' GROUP BY player.player_id,points.id_points''', [week, season])
for obj in pts:
obj.id = obj.player_id
obj.points = obj.total
obj.idpoints = obj.id_points
form = UpdatePointsForm(request.POST)
pointsf = form.save(commit=False)
pointsf.id_points = obj.idpoints
pointsf.player_id = obj.player_id
pointsf.temporada = season
pointsf.semana = week
pointsf.puntos_ppr = obj.total
pointsf.save()
return HttpResponseRedirect("/dashboard/")
else:
return HttpResponseRedirect("/savepoints/")
def savepoints(request):
actual = get_object_or_404(CurrentWeek, status='active')
week = actual.week
season = actual.season
ptsn = Player.objects.raw('''SELECT DISTINCT player.player_id,(SELECT (SELECT SUM(play_player.passing_yds))+(SELECT SUM(play_player.passing_tds))+(SELECT SUM(play_player.passing_twoptm))+(SELECT SUM(play_player.passing_int))+(SELECT SUM(play_player.rushing_yds))+(SELECT SUM(play_player.rushing_tds))+(SELECT SUM(play_player.rushing_twoptm))+(SELECT SUM(play_player.fumbles_lost))+(SELECT SUM(play_player.receiving_yds))+(SELECT SUM(play_player.receiving_tds))+(SELECT SUM(play_player.receiving_twoptm))+(SELECT SUM(play_player.receiving_rec))+(SELECT SUM(play_player.kicking_fgm))+(SELECT SUM(play_player.kicking_xpmade))+(SELECT SUM(play_player.fumbles_rec_tds))+(SELECT SUM(play_player.kicking_rec_tds))) AS total FROM player INNER JOIN play_player ON player.player_id = play_player.player_id INNER JOIN game ON play_player.gsis_id = game.gsis_id WHERE game.week = %s AND game.season_year = %s AND game.season_type != 'Warmup' AND game.season_type != 'Postseason' GROUP BY player.player_id''', [week, season])
for obj in ptsn:
obj.id = obj.player_id
obj.points = obj.total
formn = PointsForm(request.POST)
pointsfn = formn.save(commit=False)
pointsfn.player_id = obj.player_id
pointsfn.temporada = season
pointsfn.semana = week
pointsfn.points = obj.total
pointsfn.save()
return HttpResponseRedirect("/ligas/")
the forms.py:
class PointsForm(forms.ModelForm):
class Meta:
model = Points
exclude = ["player_id",
"season",
"week",
"puntos"]
class UpdatePointsForm(forms.ModelForm):
class Meta:
model = Points
exclude = ["id_points",
"player_id",
"season",
"week",
"points"]
and the models.py:
class Points(models.Model):
id_points = models.AutoField(primary_key=True, null=False, max_length=15)
player_id = models.CharField(max_length=100)
season = models.IntegerField(max_length=10)
week = models.IntegerField(max_length=10)
puntos = models.IntegerField(max_length=50)
class CurrentWeek(models.Model):
id_week = models.AutoField(primary_key=True, null=False, max_length=15)
week = models.IntegerField(max_length=10)
season = models.IntegerField(max_length=5)
status = models.CharField(max_length=50, default="done")
I'm really stumped so any help will be much appreciated.

Django advanced search

I am currently learning Django by making a web app that sell used bikes and I'm having problems with on site search.
I would like to have a search field for every model field and I just can't figure out how to do it.
What would be the best way to do this?
Any help is more than welcome!
Here is my model:
class UsedBike(models.Model):
manufacturers = (
('Aprilia', 'Aprilia'),
('Benelli', 'Benelli'),
('BMW', 'BMW'),
('Cagiva', 'Cagiva'),
('Gilera', 'Gilera'),
('Harley-Davidson', 'Harley-Davidson'),
('Husaberg', 'Husaberg'),
('Husquarna', 'Husquarna'),
('Hyosung', 'Hyosung'),
('Kawasaki', 'Kawasaki'),
('KTM', 'KTM'),
('Kymco', 'Kymco'),
('Moto Guzzi', 'Moto Guzzi'),
('MV Agusta', 'MV Agusta'),
('Suzuki', 'Suzuki'),
('Tomos', 'Tomos'),
('Triumph', 'Triumph'),
('Yamaha', 'Yamaha'),
)
manufacturer = models.CharField(help_text = 'Manufacturer: ',
max_length = 20,
choices = manufacturers)
model = models.CharField(max_length = 20, help_text = 'Model: ')
I solved this but I forgot to post the answer so that anyone who have the similar problem can use it. It is not perfect but it worked for me, if someone have a better solution feel free to answer.
In my models I have:
class UsedBike(models.Model):
manufacturer = models.CharField(max_length = 20)
model = models.CharField(max_length = 20)
year = models.PositiveIntegerField(default = 0)
bike_type = models.CharField(max_length = 20)
price = models.PositiveIntegerField(default = 0)
engine_size = models.PositiveIntegerField(default = 0)
And in views:
def searchbike(request):
man = request.GET.get('manufacturer')
mod = request.GET.get('model')
year_f = request.GET.get('year_from')
year_t = request.GET.get('year_to')
price_f = request.GET.get('price_from')
price_t = request.GET.get('price_to')
bike_t = request.GET.get('bike_type')
capacity_f = request.GET.get('cubic_capacity_from')
capacity_t = request.GET.get('cubic_capacity_to')
question_set = UsedBike.objects.filter()
if request.GET.get('manufacturer'):
question_set = question_set.filter(manufacturer__exact = man)
if request.GET.get('model'):
question_set = question_set.filter(model__icontains = mod)
if request.GET.get('year_from'):
question_set = question_set.filter(year__gte = year_f)
if request.GET.get('year_to'):
question_set = question_set.filter(year__lte = year_t)
if request.GET.get('price_from'):
question_set = question_set.filter(price__gte = price_f)
if request.GET.get('price_to'):
question_set = question_set.filter(price__lte = price_t)
if request.GET.get('bike_type'):
question_set = question_set.filter(bike_type__exact = bike_t)
if request.GET.get('cubic_capacity_from'):
question_set = question_set.filter(engine_size__gte = capacity_f)
if request.GET.get('cubic_capacity_to'):
question_set = question_set.filter(engine_size__lte = capacity_t)
return render(request, 'shop/search.html', { 'searched': question_set})
You can use django-smart-selects:
If you have the following model:
class Location(models.Model)
continent = models.ForeignKey(Continent)
country = models.ForeignKey(Country)
area = models.ForeignKey(Area)
city = models.CharField(max_length=50)
street = models.CharField(max_length=100)
And you want that if you select a continent only the countries are available that are located on this continent and the same for areas you can do the following:
from smart_selects.db_fields import ChainedForeignKey
class Location(models.Model)
continent = models.ForeignKey(Continent)
country = ChainedForeignKey(
Country,
chained_field="continent",
chained_model_field="continent",
show_all=False,
auto_choose=True
)
area = ChainedForeignKey(Area, chained_field="country", chained_model_field="country")
city = models.CharField(max_length=50)
street = models.CharField(max_length=100)

Categories

Resources