How can I save my object in an other table? - django

I have this code :
entryA = myTable1.objects.all().first()
entryB = copy.deepcopy(entryA)
But the problem is I would want to save entryB but if I do entryB.save() I will have a new entry in myTable1 whereas I want to have a new entry in myTable2 which contains the same fields.
Could you help me please ?
Thank you
Here is my model :
class myTable1(models.Model):
number = models.BooleanField(default=True)
date = models.DateField(default=None)
class myTable2(models.Model):
number = models.BooleanField(default=True)
date = models.DateField(default=None)

You'll need to copy the properties of one object to another object and then use the create method to create a new instance.
class myTable1(models.Model):
number = models.BooleanField(default=True)
date = models.DateField(default=None)
class myTable2(models.Model):
number = models.BooleanField(default=True)
date = models.DateField(default=None)
entryA = myTable1.objects.all().first()
entryB = myTable2.objects.create(number=entryA.number, date=entryA.date)
Or if you want myTable2 to have unique data, you can do:
entryA = myTable1.objects.all().first()
entryB, created = myTable2.objects.get_or_create(number=entryA.number, date=entryA.date)

Related

For each item update database

I'm a total beginner with Python/Django and trying to understand why this isn't working. I have a function that contains a for loop, doing some logic and then updating a model. but when I have more than 1 item in the loop I get a UNIQUE constraint failed: app_token.token_name error.
So I think I'm misunderstanding how the loop is working?
function
tokens = Token.objects.all()
for item in tokens:
if item.token_contract_address is not None:
token = Token.objects.get(pk=item.id)
parameters = {
'address':token.token_contract_address
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
resp = json.loads(response.text)
token_id = (resp['data'][next(iter(resp['data']))]['id'])
logo = (resp['data'][next(iter(resp['data']))]['logo'])
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
parameters = {
'id':token_id
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
id = str(token_id)
price = (json.loads(response.text)['data'][id]['quote']['USD']['price'])
market_cap = (json.loads(response.text)['data'][id]['quote']['USD']['market_cap'])
change = (json.loads(response.text)['data'][id]['quote']['USD']['percent_change_24h'])
r = Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name )
I'm expecting the this Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) to update the model based on the item loop?
The model is very simple:
class Token(models.Model):
token_name = models.CharField(max_length=50, blank=False, unique=True)
token_slug = models.CharField(max_length=50, blank=True,null=True)
token_price = models.FloatField(blank=True,null=True)
token_capture_date = models.DateField(blank=True,null=True)
token_contract_address = models.CharField(max_length=50, blank=True,null=True)
def __str__(self):
return str(self.token_name)
I'm using the update on the objects and have tried removing the token_name, and tried using token.token_name
If I remove token_name= it updates both items in the database with the same values? which makes me think its this line r = Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) do i need to apply some kinda of filter?
Thanks
I believe that by calling Token.objects.update() you actually end up trying to update all Token objects. Since token_name has to be unique, and you are giving it the same name as another Token object it throws that error.
Since you are already in a for loop, you can simply update the token that is currently being processed.
My suggestion would be to use this code instead:
item.token_capture_date = formattedDate
item.token_price = price
item.save()
This will make it so that the current token object which is being processed in the for loop has its respective field values updated and saved in the database.
Also, this line is unnecessary: token = Token.objects.get(pk=item.id) as we already have access to the token through the looping variable item.
Do let me know if this helps!

Saving Django Form With Foreign Key Reference

I have a form which references three models and I want to save the items to each model. One of the models has foreign key references to the other models and I want to save them too.
My models look like:
class Address(models.Model):
housenumber = models.CharField(max_length=20,default='',blank=True)
street = models.CharField(max_length=80,default='',blank=True)
town = models.CharField(max_length=80,default='',blank=True)
county = models.CharField(max_length=60,default='',blank=True)
country = models.CharField(max_length=20,default='',blank=True)
postcode = models.CharField(max_length=10,default='',blank=True)
class GeoLocation(models.Model):
longitude = models.FloatField(default=-4.2576300)
latitude = models.FloatField(default=55.8651500)
class Location(models.Model):
locationname = models.CharField(max_length=80,default='',blank=True)
address = models.ForeignKey(Address, on_delete=models.CASCADE)
geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='')
My views looks like:
if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
locationform.save(commit=False)
new_address = addressform.save()
new_geolocation = geolocationform.save()
locationform.address = new_address
locationform.geolocation = new_geolocation
locationform.save()
This will give me an error that states "NOT NULL constraint failed: location_location.address_id".
Can anyone help? I am new to Django so find this stuff hard.
Thanks Eduardo I managed to get it working with the following code, almost the same as yours:
if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
new_location = locationform.save(commit=False)
new_address = addressform.save()
new_geolocation = geolocationform.save()
Location.objects.create(
locationname= new_location.locationname,
address=new_address,
geolocation=new_geolocation)
One solution could be:
if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
new_address = addressform.save()
new_geolocation = geolocationform.save()
locationform.address = new_address
locationform.geolocation = new_geolocation
Location.objects.create(
locationname=locationform.data.get('locationname', " ",
address=new_address,
geolocation=new_geolocation)

Django Model inheritance and access children based on category

I want to get the parent class values with each child values? How can I identify child objects to fetch?
I have the Django model structure like this.
class Category(models.Model):
name = models.CharField(max_length=80)
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
category = models.ForeignKey('Category')
class PizzaRestaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
class PastaRestaurant(Place):
extra = models.CharField(max_length=80)
When we do operation we may save the object like below. And it saved into the db as i expected. two entry in the Place table and each entry in each child object table.
a = Category()
a.name = "pasta"
b = Category()
b.name = "pizza"
a.save()
b.save()
x = PastaRestaurant()
x.address = "Pasta Address"
x.name = "Pastamonia"
x.extra = "some extra"
x.category = a
y = PizzaRestaurant()
y.address = "Pizza Address"
y.name = "Dominos"
y.serves_hot_dogs = 1
y.serves_pizza = 0
y.category = b
x.save()
y.save()
Now I need to access the like this
p = Place.objects.get(id=1)
How can I know, which objects/attributes belongs to the place objects?
So when I fetch the place with common attributes and should be able get the corresponding child objects values also.
Or any other model design work for my need?
If you want to access the child model's attributes you need to fetch it as that model, i e PizzaRestaurant or PastaRestaurant, otherwise you will only get a Place object.
If you need to get all Places regardless of subclass take a look at InheritanceManager from django-model-utils. Using this you can implement overloaded operations to perform subclass-specific actions.
django-polymorphic does this beautifully, improving the abilities to work with model inheritance like so:
from polymorphic.models import PolymorphicModel
class Place(PolymorphicModel):
...
class PizzaRestaurant(Place):
...
class PastaRestaurant(Place:
...
>>> some_place = Place.objects.create(name="Walmart")
>>> some_pizza_place = PizzaRestaurant.objects.create(name="Slice King", address="101 Main St., Bismarck, ND", category = Category.objects.first(),serves_pizza=True)
>>> some_pizza_place.instance_of(PizzaPlace)
True
>>> PizzaRestaurant.objects.all()
queryset<['Slice King',]>
>>> Place.objects.all()
queryset<['Walmart', 'Slice King',]>

Django lookups with m2m and intermediate (through) models

I've the following django models:
class RiskOf(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True, verbose_name=_(u'catégorie'), related_name='children')
name = models.CharField(_('nom'), max_length=200)
class WorkingPlace(models.Model):
name = models.CharField(_('nom'), max_length=200)
risks = models.ManyToManyField(RiskOf, through='WorkingPlaceRisk', verbose_name=_('risques'))
class WorkingPlaceRisk(models.Model):
working_place = models.ForeignKey(WorkingPlace, verbose_name=_('poste de travail'))
risk_of = models.ForeignKey(RiskOf, blank=True, null=True, verbose_name=_(u'risque DE avérés'))
STATUS_CHOICES = (
(1, _(u'éliminé')),
(2, _(u'réduit')),
)
status = models.IntegerField(_(u'état'), max_length=1, choices=STATUS_CHOICES, null=True, blank=True)
chsct = models.BooleanField(_(u'enquête chsct'))
Given a RiskOf object (let's call it MYRISK), I need to retrieve all WorkingPlace objects which have at least one risk equal or descendant to MYRISK AND with the flag chsct set to True.
I know I can use this:
wplaces = WorkingPlace.objects.filter(workingplacerisk__risk_of__in = MYRISK.get_descendants(include_self=True))
to retrieve all WorkingPlace objects which have at least one risk equal or descendant to MYRISK, but I cant' find a way to "implement" the second condition I need, written in an horrible and clearly incorrect way I need something like (just to explain better what I need)
wplaces = WorkingPlace.objects.filter(workingplacerisk.filter(chsct=True)__risk_of__in = MYRISK.get_descendants(include_self=True))
Any ideas?
wplaces = WorkingPlace.objects.filter(workingplacerisk__risk_of__in = MYRISK.get_descendants(include_self=True) , workingplacerisk__chsct = True)

Getting related

i having problem with this:
model.py (1)
class Profession(models.Model):
user= models.ForeignKey(User,unique=True)
principal_area = models.ForeignKey(Area,verbose_name='Area principal',related_name='area_principal')
others_areas = models.ManyToManyField(Area)
model.py (2)
class Area(models.Model):
area = models.CharField(max_length=150,unique=True)
slug = models.SlugField(max_length=200)
activa = models.BooleanField(default=True)
In Model 1 i have a field "principal_area" and other "others_areas".
How ill list all professional where "principal_area" OR "others_areas" are in Area model from my views?
Sorry if im not too clear
Take a look at Django's Q objects. Here is an example of how you could go about this:
area = Area.objects.get(**conditions)
Profession.objects.filter(
Q(principal_area = area) | Q(others_areas__in = [area])
)