How to add an array of "rooms" to a "house" model in Django (SQlite) - sqlite

I'am new to Django and I'am trying to write an API to send some data from my SQLite DB.
I want the API to output something like this :
{
"name":"Yellow apartment",
"rooms":["kitchen","bathroom","bedroom"]
}
I am not sure how to handle the rooms field, since you can not store an array in SQLite DB.
Should I create a new room table for each room in the house and then set a foreign key to the house or is there any other way to handle this situation ?
class House(models.Model):
name = models.CharField(max_length=150, unique=True)
class Rooms(models.Model):
property = models.ForeignKey(House, on_delete=models.CASCADE)
KITCHEN = 'kitchen'
BATHROOM = 'bathroom'
BEDROOM = 'bedroom'
LIVING_ROOM = 'living-room'
ROOM_CHOICES = (
(KITCHEN, 'Kitchen'),
(BATHROOM, 'Bathroom'),
(BEDROOM, 'Bedroom'),
(LIVING_ROOM, 'Living Room'),
)
room_type = models.CharField(max_length=20, choices=ROOM_CHOICES)

Related

How to save objects from one database to a table in another Flask SQLAlchemy SQLlite

I am working on a project in which people can search books with ratings. The site has a login form which leads to a dashboard. I am wondering how to add books to a "saved books" list on the dashboard. I am using a SQLite Database so an array is not an option. Any suggestions for how to save books to a saved books table for each user would be greatly appreciated.
My User Model:
class User(UserMixin, userDB.Model):
id = userDB.Column(userDB.Integer, primary_key = True)
username = userDB.Column(userDB.Text(30), unique =True)
password = userDB.Column(userDB.Text(30))
My book model:
class Product(Base):
__tablename__ = "books"
title = Column(Text)
price = Column('price', Integer)
img = Column('image', String)
rating = Column('rating', String)
id = Column('id', String,primary_key=True,)
You can create a table "savedbooks", for example, in the same database with columns: id(primary key autoincrement), id_user(foreing key user) and id_book(foreing key id in books).
After you can retrieve the saved books by id of the user in "savedbooks" table.

Is it possible to convert nested Kotlin classes to a collection containing subcollections in Firestore?

Is there a simple way to convert something like this
data class Pet (
val owner: Owner = Owner()
)
data class Owner (
val name: String? = null,
val email: String? = null
)
to a Firestore collection automatically?
This doesn't work for me:
val owner = Owner("Joe", "test#test.com")
val pet = Pet("Petty", owner)
db.collection("pets").add(pet)
It's not possible. When you add() an object, it is converted to a single document. If you need to create multiple documents, then you will also need multiple calls to add() or set(), each with the data to put in the document.

How to successfully query a database for 0 applicants using LINQ

I am trying to debug this code to make sure that it queries a database for users that have zero applications for the week using LINQ. When I connect it with an HTML.ActionLink I am getting no proper filter results.
case "No_Activity":
dateCriteria = DateTime.Now.AddDays(-7);
students = students.Where(s => db.JPApplications.Where(a => a.ApplicationUserId == s.ApplicationUserId && a.JPApplicationDate >= dateCriteria).Count() == 0);
break;
You have to add ToList() because students for this is IQueryable try this :
students = students.Where(s => !db.JPApplications.Any(a => a.ApplicationUserId == s.ApplicationUserId && a.JPApplicationDate >= dateCriteria)).ToList()
and Init your date like this:
dateCriteria = DateTime.ToDay.AddDays(-7)
I replaced the count==0 by Any().
Apparently you have tables Students and Applications. There is a one-to-many relation between Students and Applications: Every Student has zero or more Applications, and every Application is owned (created by?) exactly one Student, using a foreign key.
Furthermore every Application has a (DateTime?) property ApplicationDate.
Requirement:
Given a (DateTime) variable dateCriterium, query all Students that didn't submit any Application on or after dateCriterium.
In baby steps: the Students and all applications that were submitted on or after dateCriterium:
DateTime dateCriterium = ...
IQueryable<Student> students = ...
IQueryable<Application> applicationsAfterDate = allApplications
.Where(application => application.ApplicationDate >= dateCriterium);
Extract the Ids of all Students that did submit any of these applications. Remove duplicates:
var idsOfStudentsWithApplicationsOnOrAfterDate = applicationsAfterDate
.Select(application => application.StudentId)
.Distinct();
Fetch all students that have an Id that is not in the list of student Ids of students that submitted an application on or after date = that does not contain the student Id
var studentsWithoutApplicationsOnOrAfterDate = students
.Where(student => !idsOfStudentsWithApplicationsOnOrAfterDate.Contains(student.Id));
Until now you only created the query, no the database is not queried yet:
var result = studentsWithoutApplicationsOnOrAfterDate.ToList();
TODO: if desired you can put this in one big LINQ statement. As you didn't query the database until the ToList, this won't improve performence. It surely will deteriorate the readability of the code.

Possible ways to create custom queries in Corda

We have a queryablestate for storing some information when the system is initialized, these states are issued once and never consumed
class DataState implements LinearState, QueryableState {
Party partyA;
Party partyB;
String partyAId;
String partyBId;
String sharedIdentifierNumber;
DataState(Party partyA, Party partyB, String partyAId, String partyBId, String sharedIdentifierNumber) {
this.partyA = partyA;
this.partyB = partyB;
this.partyAId = partyAId;
this.partyBId = partyBId;
this.sharedIdentifierNumber = sharedIdentifierNumber;
}
}
partyA and partyAId must be related to entity A (same for partyB)
some example instances:
new DataState(party1, party2, "00001", "12345", "0001")
new DataState(party3, party1, "05432", "00001", "0022")
new DataState(party2, party1, "12345", "00001", "0123")
we want to have methods that work like a map:
String retrievePartyId(Party party){}
assertTrue(retrievePartyId(party1).equals("00001"))
Party retrieveParty(String partyId){}
assertTrue(retrieveParty("12345").equals(party2))
we have already done this by querying all the states with custom field criteria and comparing through iteration on the
List<StateAndRef<DataState>>
We would like to know if there is some efficient way of doing this, maybe with some custom querycriteria in Corda. We think this is related to sql column projections. The query interface returns list of 'states(.getStates())' OR aggregation results '(.getOtherResults())'. We were wondering if it’s possible (or planned) to get a single column from the db and then filter the duplicates through the vault interface, currently we’re doing that in java.
If your states are QueryableStates, they can be efficiently queried based on their schema's attributes.
For example, suppose in the CorDapp Example (https://github.com/corda/cordapp-example), I wanted to query the vault for IOUStates based on their value and whether I am the lender. I could do this as follows:
try {
Field value = IOUSchemaV1.PersistentIOU.class.getDeclaredField("value");
Field lender = IOUSchemaV1.PersistentIOU.class.getDeclaredField("lender");
QueryCriteria valueOver50Criteria = new QueryCriteria.VaultCustomQueryCriteria(greaterThan(value, 50));
QueryCriteria lenderIsMeCriteria = new QueryCriteria.VaultCustomQueryCriteria(equal(lender, getOurIdentity().getName().toString()));
QueryCriteria criteria = valueOver50Criteria.and(lenderIsMeCriteria);
Vault.Page<IOUState> results = getServiceHub().getVaultService().queryBy(IOUState.class, criteria);
List<StateAndRef<IOUState>> matchingStates = results.getStates();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
In your case, you would be querying based on the party's ID or the party's name. You would then take the first result and use it to map the party's name to the party's ID, or vice-versa.

MVC List Not Working as it should

So the issue that I am having is getting the correct db items to work in the search in the web page, for some reason it does not search all of the values from Vehicle_Make that exist in Vehicle_Details - Make_ID is the primary key of Vehicle_Make and it is a FK in Vehicle_Details.
What happens is, it shows all the items on the page in a list, but the search does not work when I search for any of those items.
public class MapController : Controller
{
private GoogleMapEntities db = new GoogleMapEntities();
// GET: Map
public ActionResult Index()
{
GoogleMapEntities GE = new GoogleMapEntities();
List<Vehicle_Details> vehList = db.Vehicle_Details.ToList();
GoogleMapViewModel GMviewmodel = new GoogleMapViewModel();
List<GoogleMapViewModel> GMviewmodelList = vehList.Select(x=> new GoogleMapViewModel {
Make_Name = x.Vehicle_Make.Make_Name,
Make_ID = x.Vehicle_Make.Make_ID,
User_ID = x.User.User_ID,
MapLat = x.User.MapLat,
MapLong = x.User.MapLong
// Dealer_name = x.User.Dealer_name
}).ToList();
return View(GMviewmodelList);
}
[HttpPost]
public ActionResult Search(string Location)
{
GoogleMapEntities GE = new GoogleMapEntities();
////SELECT Make_Name DATA FROM DB1
var result = GE.Vehicle_Make.Where(x => x.Make_Name.StartsWith(Location)).ToList();
var GetVeh = (from vd in db.Vehicle_Details
join vm in db.Vehicle_Make
on vd.Make_ID equals vm.Make_ID
join u in db.User
on vd.User_ID equals u.User_ID
select vm).ToList();
//SELECT ALL ELEMENTS FROM Veh Make TABLE THAT EXISTS ON Veh Details TABLE BASED ON EXISTING ID's
var resultFinal = (from e in result
where !(from m in GetVeh
select m.Make_ID).Contains(e.Make_ID)
select e
).ToList();
return Json(resultFinal, JsonRequestBehavior.AllowGet);
}
}
Another weird thing that happens is, if I add the "!" in the following code, it does return the vehicle makes that do not exist in the vehicle details table but without the "!", it does not search for the values that do exist in both tables.
var resultFinal = (from e in result
where !(from m in GetVeh
select m.Make_ID).Contains(e.Make_ID)
select e
).ToList();
Sample Data:
BMW exists in Vehicle_Make(Make_ID PK) and Vehicle_Details(Make_ID FK).
Vespa exists in Vehicle_Make but not in Vehicle_Details
If I search for BMW it does not work but if I search for Vespa or any vehicle that does not exist in the Vehicle_Details table, it will find those, but not the vehicles that exist in both tables.
Once I get the correct items that need to be searched for like BMW, it must match the Dealerships(Users table) and take the MapLat & MapLong from the "Users" table and then pin point them onto the map.
Vehicle_Details has (User_ID FK) which is the PK of the Users Table.
Basically, Vehicle_Details has Users and Vehicle_Make linked to it, while Users and Vehicle_Make do not have a link in them so therefore vehicle details is the link. Is this possible to make work for what I require?

Resources