I have 2 models one defines all the all the devices that I have, and the other stores the information that the devices are obtaining. The code of they is the following,
class Device(models.Model):
dev_eui = models.CharField(max_length=16, primary_key=True)
producer = models.CharField(max_length=20, blank=True, null=True)
model = models.CharField(max_length=20, blank=True, null=True)
firmware = models.CharField(max_length=10, blank=True, null=True)
dev_name = models.CharField(max_length=20, blank=True, null=True)
description = models.CharField(max_length=40, blank=True, null=True)
fixed = models.BooleanField()
dev_lat = models.FloatField(null=True, blank=True)
dev_lon = models.FloatField(null=True, blank=True)
deco_name = models.CharField(max_length=20)
fleet_id = models.IntegerField(null=True, blank=True)
class DevData(models.Model):
data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
data_id = models.IntegerField()
dev_eui = models.CharField(max_length=16)
gateway = models.CharField(max_length=25)
data_timestamp = models.DateTimeField()
rssi = models.IntegerField()
snr = models.IntegerField()
datarate = models.CharField(max_length=15)
frequency = models.IntegerField()
seq = models.IntegerField()
data_1 = models.FloatField()
data_2 = models.FloatField(null=True, blank=True)
data_3 = models.FloatField(null=True, blank=True)
data_4 = models.FloatField(null=True, blank=True)
data_5 = models.FloatField(null=True, blank=True)
data_6 = models.FloatField(null=True, blank=True)
data_7 = models.FloatField(null=True, blank=True)
Actually what I want is show a table in my template, combining all the data from devData and adding the dev_name and fleet_id from devices.
Now what I'm doing is obtaining all the data and in the template filtering it. But I'm sure it's better and easier doing this in the views.py, but I don't know how.
Reading some info, I found the union() function but it's not working and I'm not sure if is the best option,
#login_required(login_url='/user_app/login/')
def user_data(request):
dev_data = DevData.objects.all()
devices = Device.objects.all()
test = DevData.objects.all().values_list(
"dev_eui"
).union(
Device.objects.all().values_list(
"dev_eui"
))
ctx = {'DevData':dev_data,'Devices':devices, 'Test':test}
return render(request, template_name='data.html', context=ctx)
This join shows nothing.
Can somebody help me? Thank very much!
You need a foreign key relating the two models.
class Device(models.Model):
dev_eui = models.CharField(max_length=16, primary_key=True)
class DevData(models.Model):
device = models.ForeignKeyField(Device, related_name='dev_data', on_delete=models.CASCADE)
data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
data_id = models.IntegerField()
# This is not needed, it can be accessed via instance.device.dev_eui now
# dev_eui = models.CharField(max_length=16)
Then to get all of the DevData instances for a particular device:
for device in Device.objects.all():
x = device.dev_data.all()
Please read the documentation to better understand relationship fields.
Related
I can use some help on a query using 3 tables. Here is what my models contains.
class VolunteerRecord(models.Model):
eventname = models.CharField(help_text=_('Name of the event'),max_length=256, blank=False, default='')
category = models.CharField(max_length=256, blank=False, choices=CATEGORY_CHOICES)
hours = models.FloatField(blank=False)
date=models.DateField(help_text=_('Enter the date of the event'),validators=MaxValueValidator(limit_value=date.today)])
mileage = models.FloatField(blank=True, null=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
streetaddress1 = models.CharField(blank=True, max_length=256)
streetaddress2 = models.CharField(blank=True, max_length=256)
city = models.CharField(blank=True, max_length=30)
state = models.CharField(max_length=256, blank=False, choices=US_STATES)
zipcode = models.CharField(blank=True, max_length=15)
county = models.CharField(max_length=256, blank=False, choices=STATE_COUNTIES)
I would like to filter all VolunteerRecords where the owner's county = request.user's county
So far I have... (not sure what I am suppose to put where my ??? are)
def history(request):
current_user_county = request.user.profile.county
records = VolunteerRecord.objects.filter(????=current_user_county)
I was able to figure it our with your help.
records = VolunteerRecord.objects.filter(owner__profile__county=request.user.profile.county)
I am fairly new to django rest framework, and I am trying to make a model which is associated with two users, one as assigner and the other as assignee. I tried adding two different foreign keys, but it throws error. Here is my code:
job = models.ForeignKey(Job,related_name='Job',on_delete=models.CASCADE, null=True)
assigner = models.ForeignKey(User, on_delete=models.PROTECT, null=True)
assignee = models.ForeignKey(User, on_delete=models.PROTECT, null=True)
unit = models.ForeignKey(Unit,related_name='UnitName',on_delete=models.CASCADE, null=True)
equipment = models.ForeignKey(Equipment,related_name='EquipmentName',on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=200)
category = models.CharField(max_length=200, null=True,blank=True)
start_date = models.DateField()
end_date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True,blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True,blank=True, null=True)
status = models.ForeignKey(TaskStatus, related_name='Status',on_delete=models.CASCADE)
def __str__(self):
return(self.name)
Please help
I have been working on a e-commerce project. I have three models Item, OrderItem, Order. They are linked with Foreignkey(s) (Item -> OrderItem -> Order). Item is the actual product and an Order contain(s) Item(s).
Item basically represents a product. In Item there is an attribute 'price' which needs to updated as need suggest. Like during a sale or something else.
What happens is when I update the price of an Item, the price of that item also gets updated in the instances of the Order(s) that are already completed.
Basically I would want to separate these models in a way such that any changes in the Item model doesn't effect the Orders that are completed.
class Item(models.Model):
title = models.CharField(max_length=100)
sku = models.CharField(max_length=8, validators=[
MinLengthValidator(8)], unique=True)
upc = models.CharField(max_length=12, validators=[
MinLengthValidator(12)], unique=True, blank=True, null=True)
date_updated = models.DateTimeField(
auto_now=True, blank=True, null=True)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
image = models.ImageField(upload_to=upload_location, blank=True, null=True)
stock_quantity = models.IntegerField(default=0)
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
item_variations = models.ManyToManyField(ItemVariation)
quantity = models.IntegerField(default=1)
purchase = models.FloatField(blank=True, null=True)
def get_total_item_price(self):
return self.quantity * self.item.price
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
ref_code = models.CharField(
max_length=20, blank=True, null=True, unique=True)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
# Check this
ordered_date = models.DateTimeField()
# When the payment is made it becomes True
ordered = models.BooleanField(default=False)
shipping_address = models.ForeignKey(
'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True)
billing_address = models.ForeignKey(
'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True)
payment = models.ForeignKey(
'Payment', on_delete=models.SET_NULL, blank=True, null=True)
coupon = models.ForeignKey(
'Coupon', on_delete=models.SET_NULL, blank=True, null=True)
being_delivered = models.BooleanField(default=False)
received = models.BooleanField(default=False)
refund_requested = models.BooleanField(default=False)
refund_granted = models.BooleanField(default=False)
refund_refused = models.BooleanField(default=False)
Any help will be appreciated, thank you.
You could have ItemPrice as a separate model with a One-to-Many relationship. Which prices for the item are stored with associated date changed.
models.py
class ItemPrice(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
price = models.FloatField()
date_changed = models.DateTimeField(auto_now=True, blank=True, null=True)
Then align your order date with the items price at that current time.
I want to add one subquery to my query. And I created a #property in Transaction. Found on the Internet that this is what I need. But I do not fully understand how they work. How to use it?
views.py(Query)
paymentsss = Transaction.objects.all().select_related('currency',
'payment_source__payment_type',
'deal__service__contractor',).
models.py
class PayerPaymentSource(models.Model):
id = models.BigIntegerField(blank=True, null=False, primary_key=True)
payer_id = models.BigIntegerField(blank=True, null=True)
payment_type = models.ForeignKey(PaymentType, max_length=64, blank=True, null=True, on_delete=models.CASCADE)
source_details = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = '"processing"."payer_payment_source"'
class Transaction(models.Model):
id = models.BigIntegerField(blank=True, null=False, primary_key=True)
currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE)
deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE)
# service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE)
payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE)
payment_date = models.DateTimeField(blank=True, null=True)
amount = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
context = models.TextField(blank=True, null=True)
#property
def bank_card_details(self):
return PayerPaymentSource.objects.filter(self.payment_source.source_details,
payment_type='bank_card_details')
class Meta:
managed = False
db_table = '"processing"."transaction"'
UPD: print(payment.bank_card_details) works, but it creates a lot of similar queries. How to fix it?
The #property decorator is just a convenient way to call the property() function, which is built in to Python. This function returns a special descriptor object which allows direct access to the method's computed value.
For example in your view
obj = Transaction.objects.get(pk=pk)
#now you can get the bank_card_details like this:
print(obj.bank_card_details)
I'm working with a legay database so I have to set managed = False, which means I cannot update the database schema.
What I'm trying to do is select branches based on project id. Ideally in branches table it should have a project_id as foreign key but the previous system design is another table (branches_projects) stores this relationship.
I have been able to get around some problems using https://docs.djangoproject.com/en/1.11/topics/db/sql/#django.db.models.Manager.raw. raw() would return an RawQuerySet, which is not ideal.
I wonder if there's a way for me to define a foreign key in my branches table, which is the project_id, but refer/link that to the branches_projects table?
class Branches(models.Model):
name = models.CharField(max_length=128)
branchpoint_str = models.CharField(max_length=255)
dev_lead_id = models.IntegerField(blank=True, null=True)
source = models.CharField(max_length=255)
state = models.CharField(max_length=255)
kind = models.CharField(max_length=255)
desc = models.TextField(blank=True, null=True)
approved = models.IntegerField()
for_customer = models.IntegerField()
deactivated_at = models.DateTimeField(blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
codb_id = models.IntegerField(blank=True, null=True)
pm_lead_id = models.IntegerField(blank=True, null=True)
version = models.CharField(max_length=20, blank=True, null=True)
path_id = models.IntegerField(blank=True, null=True)
branchpoint_type = models.CharField(max_length=255, blank=True, null=True)
branchpoint_id = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'branches'
verbose_name_plural = 'Branches'
class Projects(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=40, primary_key=True)
status = models.CharField(max_length=255)
platform = models.CharField(max_length=255)
enabled = models.IntegerField()
path = models.CharField(max_length=128, blank=True, null=True)
tag_prefix = models.CharField(max_length=64, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
codb_id = models.IntegerField(blank=True, null=True)
template = models.CharField(max_length=64, blank=True, null=True)
image_path = models.CharField(max_length=128, blank=True, null=True)
repository_id = models.IntegerField(blank=True, null=True)
number_scheme = models.CharField(max_length=32)
special_dir = models.CharField(max_length=32, blank=True, null=True)
project_family_id = models.IntegerField()
class Meta:
managed = False
db_table = 'projects'
verbose_name_plural = 'projects'
class BranchesProjects(models.Model):
# project_id = models.IntegerField()
# branch_id = models.IntegerField()
project = models.ForeignKey(Projects, on_delete=models.CASCADE)
branch = models.ForeignKey(Branches, on_delete=models.CASCADE)
class Meta:
managed = False
db_table = 'branches_projects'
My current raw query is like this
SELECT br.id, br.name, br.created_at, br.updated_at,
br.branchpoint_str, br.source
FROM branches as br
LEFT JOIN branches_projects as bp
ON br.id = bp.branch_id
WHERE bp.project_id = %s AND source != 'other'
ORDER BY updated_at DESC
I've finally got it working......
In the model, I use the manytomany as following:
class Branches(models.Model):
name = models.CharField(max_length=128)
project = models.ManyToManyField(Projects,
through='BranchesProjects',
related_name='project')
branchpoint_str = models.CharField(max_length=255)
Then to get the same result as my raw sql, i do the following:
def get_sb(project_id):
result = Branches.objects.filter(
project=Projects.objects.get(id=project_id).id,
).exclude(source='other').order_by('-updated_at')
print result.query
return result