Getting related - django

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

Related

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)

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)

Django query related objects

I have models like this:
class A(Model):
....
class B(Model):
a = ForeignKey(A, related_name="bbb")
class C(Model)
b = ForeignKey(B, related_name="ccc")
file = FileField( ... , null=True, blank=True)
In template or in view I need a mark A row, if some C object related to A has file=None (null) .
Thanks.
If I understand correctly, try this:
for a in A.objects.all():
for b in a.bbb.all():
for c in b.ccc.filter(file__isnull=True):
a.has_c_with_null_file = True
a.save()
OR
c_without_file = C.objects.filter(file__isnull=True)
for c in c_without_file:
c.b.a.has_c_with_null_file = True
c.b.a.save()
OR
A.objects.filter(b__c__file__isnull=True).update(has_c_with_null_file=True)
If you leave off the related name, use b_set and c_set.