Saving Django Form With Foreign Key Reference - django

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)

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!

Trying to change IntegerProperty to FloatProperty of existing AppEngine DataStore. Getting error Indexed value must be at most 1500 bytes

BEFORE :
class Person(ndb.Model):
name = ndb.StringProperty()
age = ndb.StringProperty()
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
class OtherDetails(ndb.Model):
success = ndb.StringProperty()
qr_code = ndb.TextProperty()
AFTER:
class Person(ndb.Expando):
pass
rows_to_be_updated = []
for person in Person.all():
person.age = int(person.age)
rows_to_be_updated.append(person)
if len(rows_to_be_updated)>0:
ndb.put_multi_async(rows_to_be_updated)
#"When the above line is executed i am getting error"
Very AFTER:
class Person(db.Model):
name = db.StringProperty()
age = db.IntegerProperty()
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
As per the datastore document, the TextProperty is unindexed by default. What is the reason for the error? I have tried making explicit Indexed=False (ndb.TextProperty(indexed= False)) but didn't work.
Instead of trying to go through an expando model, you might consider using a different name in your database than in your model.
E.g. after
class Person(ndb.Model):
name = ndb.StringProperty()
string_age = ndb.StringProperty('age')
age = ndb.IntegerProperty('int_age')
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
Then you could use a hook to ensure that Person.age is always set, e.g.
class Person(ndb.Model):
#classmethod
def _post_get_hook(cls, key, future):
p = future.get_result()
if p and not p.age:
p.age = int(p.string_age)

How can I save my object in an other table?

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)

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',]>

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])
)